babylon.max.js 4.6 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142871438714487145871468714787148871498715087151871528715387154871558715687157871588715987160871618716287163871648716587166871678716887169871708717187172871738717487175871768717787178871798718087181871828718387184871858718687187871888718987190871918719287193871948719587196871978719887199872008720187202872038720487205872068720787208872098721087211872128721387214872158721687217872188721987220872218722287223872248722587226872278722887229872308723187232872338723487235872368723787238872398724087241872428724387244872458724687247872488724987250872518725287253872548725587256872578725887259872608726187262872638726487265872668726787268872698727087271872728727387274872758727687277872788727987280872818728287283872848728587286872878728887289872908729187292872938729487295872968729787298872998730087301873028730387304873058730687307873088730987310873118731287313873148731587316873178731887319873208732187322873238732487325873268732787328873298733087331873328733387334873358733687337873388733987340873418734287343873448734587346873478734887349873508735187352873538735487355873568735787358873598736087361873628736387364873658736687367873688736987370873718737287373873748737587376873778737887379873808738187382873838738487385873868738787388873898739087391873928739387394873958739687397873988739987400874018740287403874048740587406874078740887409874108741187412874138741487415874168741787418874198742087421874228742387424874258742687427874288742987430874318743287433874348743587436874378743887439874408744187442874438744487445874468744787448874498745087451874528745387454874558745687457874588745987460874618746287463874648746587466874678746887469874708747187472874738747487475874768747787478874798748087481874828748387484874858748687487874888748987490874918749287493874948749587496874978749887499875008750187502875038750487505875068750787508875098751087511875128751387514875158751687517875188751987520875218752287523875248752587526875278752887529875308753187532875338753487535875368753787538875398754087541875428754387544875458754687547875488754987550875518755287553875548755587556875578755887559875608756187562875638756487565875668756787568875698757087571875728757387574875758757687577875788757987580875818758287583875848758587586875878758887589875908759187592875938759487595875968759787598875998760087601876028760387604876058760687607876088760987610876118761287613876148761587616876178761887619876208762187622876238762487625876268762787628876298763087631876328763387634876358763687637876388763987640876418764287643876448764587646876478764887649876508765187652876538765487655876568765787658876598766087661876628766387664876658766687667876688766987670876718767287673876748767587676876778767887679876808768187682876838768487685876868768787688876898769087691876928769387694876958769687697876988769987700877018770287703877048770587706877078770887709877108771187712877138771487715877168771787718877198772087721877228772387724877258772687727877288772987730877318773287733877348773587736877378773887739877408774187742877438774487745877468774787748877498775087751877528775387754877558775687757877588775987760877618776287763877648776587766877678776887769877708777187772877738777487775877768777787778877798778087781877828778387784877858778687787877888778987790877918779287793877948779587796877978779887799878008780187802878038780487805878068780787808878098781087811878128781387814878158781687817878188781987820878218782287823878248782587826878278782887829878308783187832878338783487835878368783787838878398784087841878428784387844878458784687847878488784987850878518785287853878548785587856878578785887859878608786187862878638786487865878668786787868878698787087871878728787387874878758787687877878788787987880878818788287883878848788587886878878788887889878908789187892878938789487895878968789787898878998790087901879028790387904879058790687907879088790987910879118791287913879148791587916879178791887919879208792187922879238792487925879268792787928879298793087931879328793387934879358793687937879388793987940879418794287943879448794587946879478794887949879508795187952879538795487955879568795787958879598796087961879628796387964879658796687967879688796987970879718797287973879748797587976879778797887979879808798187982879838798487985879868798787988879898799087991879928799387994879958799687997879988799988000880018800288003880048800588006880078800888009880108801188012880138801488015880168801788018880198802088021880228802388024880258802688027880288802988030880318803288033880348803588036880378803888039880408804188042880438804488045880468804788048880498805088051880528805388054880558805688057880588805988060880618806288063880648806588066880678806888069880708807188072880738807488075880768807788078880798808088081880828808388084880858808688087880888808988090880918809288093880948809588096880978809888099881008810188102881038810488105881068810788108881098811088111881128811388114881158811688117881188811988120881218812288123881248812588126881278812888129881308813188132881338813488135881368813788138881398814088141881428814388144881458814688147881488814988150881518815288153881548815588156881578815888159881608816188162881638816488165881668816788168881698817088171881728817388174881758817688177881788817988180881818818288183881848818588186881878818888189881908819188192881938819488195881968819788198881998820088201882028820388204882058820688207882088820988210882118821288213882148821588216882178821888219882208822188222882238822488225882268822788228882298823088231882328823388234882358823688237882388823988240882418824288243882448824588246882478824888249882508825188252882538825488255882568825788258882598826088261882628826388264882658826688267882688826988270882718827288273882748827588276882778827888279882808828188282882838828488285882868828788288882898829088291882928829388294882958829688297882988829988300883018830288303883048830588306883078830888309883108831188312883138831488315883168831788318883198832088321883228832388324883258832688327883288832988330883318833288333883348833588336883378833888339883408834188342883438834488345883468834788348883498835088351883528835388354883558835688357883588835988360883618836288363883648836588366883678836888369883708837188372883738837488375883768837788378883798838088381883828838388384883858838688387883888838988390883918839288393883948839588396883978839888399884008840188402884038840488405884068840788408884098841088411884128841388414884158841688417884188841988420884218842288423884248842588426884278842888429884308843188432884338843488435884368843788438884398844088441884428844388444884458844688447884488844988450884518845288453884548845588456884578845888459884608846188462884638846488465884668846788468884698847088471884728847388474884758847688477884788847988480884818848288483884848848588486884878848888489884908849188492884938849488495884968849788498884998850088501885028850388504885058850688507885088850988510885118851288513885148851588516885178851888519885208852188522885238852488525885268852788528885298853088531885328853388534885358853688537885388853988540885418854288543885448854588546885478854888549885508855188552885538855488555885568855788558885598856088561885628856388564885658856688567885688856988570885718857288573885748857588576885778857888579885808858188582885838858488585885868858788588885898859088591885928859388594885958859688597885988859988600886018860288603886048860588606886078860888609886108861188612886138861488615886168861788618886198862088621886228862388624886258862688627886288862988630886318863288633886348863588636886378863888639886408864188642886438864488645886468864788648886498865088651886528865388654886558865688657886588865988660886618866288663886648866588666886678866888669886708867188672886738867488675886768867788678886798868088681886828868388684886858868688687886888868988690886918869288693886948869588696886978869888699887008870188702887038870488705887068870788708887098871088711887128871388714887158871688717887188871988720887218872288723887248872588726887278872888729887308873188732887338873488735887368873788738887398874088741887428874388744887458874688747887488874988750887518875288753887548875588756887578875888759887608876188762887638876488765887668876788768887698877088771887728877388774887758877688777887788877988780887818878288783887848878588786887878878888789887908879188792887938879488795887968879788798887998880088801888028880388804888058880688807888088880988810888118881288813888148881588816888178881888819888208882188822888238882488825888268882788828888298883088831888328883388834888358883688837888388883988840888418884288843888448884588846888478884888849888508885188852888538885488855888568885788858888598886088861888628886388864888658886688867888688886988870888718887288873888748887588876888778887888879888808888188882888838888488885888868888788888888898889088891888928889388894888958889688897888988889988900889018890288903889048890588906889078890888909889108891188912889138891488915889168891788918889198892088921889228892388924889258892688927889288892988930889318893288933889348893588936889378893888939889408894188942889438894488945889468894788948889498895088951889528895388954889558895688957889588895988960889618896288963889648896588966889678896888969889708897188972889738897488975889768897788978889798898088981889828898388984889858898688987889888898988990889918899288993889948899588996889978899888999890008900189002890038900489005890068900789008890098901089011890128901389014890158901689017890188901989020890218902289023890248902589026890278902889029890308903189032890338903489035890368903789038890398904089041890428904389044890458904689047890488904989050890518905289053890548905589056890578905889059890608906189062890638906489065890668906789068890698907089071890728907389074890758907689077890788907989080890818908289083890848908589086890878908889089890908909189092890938909489095890968909789098890998910089101891028910389104891058910689107891088910989110891118911289113891148911589116891178911889119891208912189122891238912489125891268912789128891298913089131891328913389134891358913689137891388913989140891418914289143891448914589146891478914889149891508915189152891538915489155891568915789158891598916089161891628916389164891658916689167891688916989170891718917289173891748917589176891778917889179891808918189182891838918489185891868918789188891898919089191891928919389194891958919689197891988919989200892018920289203892048920589206892078920889209892108921189212892138921489215892168921789218892198922089221892228922389224892258922689227892288922989230892318923289233892348923589236892378923889239892408924189242892438924489245892468924789248892498925089251892528925389254892558925689257892588925989260892618926289263892648926589266892678926889269892708927189272892738927489275892768927789278892798928089281892828928389284892858928689287892888928989290892918929289293892948929589296892978929889299893008930189302893038930489305893068930789308893098931089311893128931389314893158931689317893188931989320893218932289323893248932589326893278932889329893308933189332893338933489335893368933789338893398934089341893428934389344893458934689347893488934989350893518935289353893548935589356893578935889359893608936189362893638936489365893668936789368893698937089371893728937389374893758937689377893788937989380893818938289383893848938589386893878938889389893908939189392893938939489395893968939789398893998940089401894028940389404894058940689407894088940989410894118941289413894148941589416894178941889419894208942189422894238942489425894268942789428894298943089431894328943389434894358943689437894388943989440894418944289443894448944589446894478944889449894508945189452894538945489455894568945789458894598946089461894628946389464894658946689467894688946989470894718947289473894748947589476894778947889479894808948189482894838948489485894868948789488894898949089491894928949389494894958949689497894988949989500895018950289503895048950589506895078950889509895108951189512895138951489515895168951789518895198952089521895228952389524895258952689527895288952989530895318953289533895348953589536895378953889539895408954189542895438954489545895468954789548895498955089551895528955389554895558955689557895588955989560895618956289563895648956589566895678956889569895708957189572895738957489575895768957789578895798958089581895828958389584895858958689587895888958989590895918959289593895948959589596895978959889599896008960189602896038960489605896068960789608896098961089611896128961389614896158961689617896188961989620896218962289623896248962589626896278962889629896308963189632896338963489635896368963789638896398964089641896428964389644896458964689647896488964989650896518965289653896548965589656896578965889659896608966189662896638966489665896668966789668896698967089671896728967389674896758967689677896788967989680896818968289683896848968589686896878968889689896908969189692896938969489695896968969789698896998970089701897028970389704897058970689707897088970989710897118971289713897148971589716897178971889719897208972189722897238972489725897268972789728897298973089731897328973389734897358973689737897388973989740897418974289743897448974589746897478974889749897508975189752897538975489755897568975789758897598976089761897628976389764897658976689767897688976989770897718977289773897748977589776897778977889779897808978189782897838978489785897868978789788897898979089791897928979389794897958979689797897988979989800898018980289803898048980589806898078980889809898108981189812898138981489815898168981789818898198982089821898228982389824898258982689827898288982989830898318983289833898348983589836898378983889839898408984189842898438984489845898468984789848898498985089851898528985389854898558985689857898588985989860898618986289863898648986589866898678986889869898708987189872898738987489875898768987789878898798988089881898828988389884898858988689887898888988989890898918989289893898948989589896898978989889899899008990189902899038990489905899068990789908899098991089911899128991389914899158991689917899188991989920899218992289923899248992589926899278992889929899308993189932899338993489935899368993789938899398994089941899428994389944899458994689947899488994989950899518995289953899548995589956899578995889959899608996189962899638996489965899668996789968899698997089971899728997389974899758997689977899788997989980899818998289983899848998589986899878998889989899908999189992899938999489995899968999789998899999000090001900029000390004900059000690007900089000990010900119001290013900149001590016900179001890019900209002190022900239002490025900269002790028900299003090031900329003390034900359003690037900389003990040900419004290043900449004590046900479004890049900509005190052900539005490055900569005790058900599006090061900629006390064900659006690067900689006990070900719007290073900749007590076900779007890079900809008190082900839008490085900869008790088900899009090091900929009390094900959009690097900989009990100901019010290103901049010590106901079010890109901109011190112901139011490115901169011790118901199012090121901229012390124901259012690127901289012990130901319013290133901349013590136901379013890139901409014190142901439014490145901469014790148901499015090151901529015390154901559015690157901589015990160901619016290163901649016590166901679016890169901709017190172901739017490175901769017790178901799018090181901829018390184901859018690187901889018990190901919019290193901949019590196901979019890199902009020190202902039020490205902069020790208902099021090211902129021390214902159021690217902189021990220902219022290223902249022590226902279022890229902309023190232902339023490235902369023790238902399024090241902429024390244902459024690247902489024990250902519025290253902549025590256902579025890259902609026190262902639026490265902669026790268902699027090271902729027390274902759027690277902789027990280902819028290283902849028590286902879028890289902909029190292902939029490295902969029790298902999030090301903029030390304903059030690307903089030990310903119031290313903149031590316903179031890319903209032190322903239032490325903269032790328903299033090331903329033390334903359033690337903389033990340903419034290343903449034590346903479034890349903509035190352903539035490355903569035790358903599036090361903629036390364903659036690367903689036990370903719037290373903749037590376903779037890379903809038190382903839038490385903869038790388903899039090391903929039390394903959039690397903989039990400904019040290403904049040590406904079040890409904109041190412904139041490415904169041790418904199042090421904229042390424904259042690427904289042990430904319043290433904349043590436904379043890439904409044190442904439044490445904469044790448904499045090451904529045390454904559045690457904589045990460904619046290463904649046590466904679046890469904709047190472904739047490475904769047790478904799048090481904829048390484904859048690487904889048990490904919049290493904949049590496904979049890499905009050190502905039050490505905069050790508905099051090511905129051390514905159051690517905189051990520905219052290523905249052590526905279052890529905309053190532905339053490535905369053790538905399054090541905429054390544905459054690547905489054990550905519055290553905549055590556905579055890559905609056190562905639056490565905669056790568905699057090571905729057390574905759057690577905789057990580905819058290583905849058590586905879058890589905909059190592905939059490595905969059790598905999060090601906029060390604906059060690607906089060990610906119061290613906149061590616906179061890619906209062190622906239062490625906269062790628906299063090631906329063390634906359063690637906389063990640906419064290643906449064590646906479064890649906509065190652906539065490655906569065790658906599066090661906629066390664906659066690667906689066990670906719067290673906749067590676906779067890679906809068190682906839068490685906869068790688906899069090691906929069390694906959069690697906989069990700907019070290703907049070590706907079070890709907109071190712907139071490715907169071790718907199072090721907229072390724907259072690727907289072990730907319073290733907349073590736907379073890739907409074190742907439074490745907469074790748907499075090751907529075390754907559075690757907589075990760907619076290763907649076590766907679076890769907709077190772907739077490775907769077790778907799078090781907829078390784907859078690787907889078990790907919079290793907949079590796907979079890799908009080190802908039080490805908069080790808908099081090811908129081390814908159081690817908189081990820908219082290823908249082590826908279082890829908309083190832908339083490835908369083790838908399084090841908429084390844908459084690847908489084990850908519085290853908549085590856908579085890859908609086190862908639086490865908669086790868908699087090871908729087390874908759087690877908789087990880908819088290883908849088590886908879088890889908909089190892908939089490895908969089790898908999090090901909029090390904909059090690907909089090990910909119091290913909149091590916909179091890919909209092190922909239092490925909269092790928909299093090931909329093390934909359093690937909389093990940909419094290943909449094590946909479094890949909509095190952909539095490955909569095790958909599096090961909629096390964909659096690967909689096990970909719097290973909749097590976909779097890979909809098190982909839098490985909869098790988909899099090991909929099390994909959099690997909989099991000910019100291003910049100591006910079100891009910109101191012910139101491015910169101791018910199102091021910229102391024910259102691027910289102991030910319103291033910349103591036910379103891039910409104191042910439104491045910469104791048910499105091051910529105391054910559105691057910589105991060910619106291063910649106591066910679106891069910709107191072910739107491075910769107791078910799108091081910829108391084910859108691087910889108991090910919109291093910949109591096910979109891099911009110191102911039110491105911069110791108911099111091111911129111391114911159111691117911189111991120911219112291123911249112591126911279112891129911309113191132911339113491135911369113791138911399114091141911429114391144911459114691147911489114991150911519115291153911549115591156911579115891159911609116191162911639116491165911669116791168911699117091171911729117391174911759117691177911789117991180911819118291183911849118591186911879118891189911909119191192911939119491195911969119791198911999120091201912029120391204912059120691207912089120991210912119121291213912149121591216912179121891219912209122191222912239122491225912269122791228912299123091231912329123391234912359123691237912389123991240912419124291243912449124591246912479124891249912509125191252912539125491255912569125791258912599126091261912629126391264912659126691267912689126991270912719127291273912749127591276912779127891279912809128191282912839128491285912869128791288912899129091291912929129391294912959129691297912989129991300913019130291303913049130591306913079130891309913109131191312913139131491315913169131791318913199132091321913229132391324913259132691327913289132991330913319133291333913349133591336913379133891339913409134191342913439134491345913469134791348913499135091351913529135391354913559135691357913589135991360913619136291363913649136591366913679136891369913709137191372913739137491375913769137791378913799138091381913829138391384913859138691387913889138991390913919139291393913949139591396913979139891399914009140191402914039140491405914069140791408914099141091411914129141391414914159141691417914189141991420914219142291423914249142591426914279142891429914309143191432914339143491435914369143791438914399144091441914429144391444914459144691447914489144991450914519145291453914549145591456914579145891459914609146191462914639146491465914669146791468914699147091471914729147391474914759147691477914789147991480914819148291483914849148591486914879148891489914909149191492914939149491495914969149791498914999150091501915029150391504915059150691507915089150991510915119151291513915149151591516915179151891519915209152191522915239152491525915269152791528915299153091531915329153391534915359153691537915389153991540915419154291543915449154591546915479154891549915509155191552915539155491555915569155791558915599156091561915629156391564915659156691567915689156991570915719157291573915749157591576915779157891579915809158191582915839158491585915869158791588915899159091591915929159391594915959159691597915989159991600916019160291603916049160591606916079160891609916109161191612916139161491615916169161791618916199162091621916229162391624916259162691627916289162991630916319163291633916349163591636916379163891639916409164191642916439164491645916469164791648916499165091651916529165391654916559165691657916589165991660916619166291663916649166591666916679166891669916709167191672916739167491675916769167791678916799168091681916829168391684916859168691687916889168991690916919169291693916949169591696916979169891699917009170191702917039170491705917069170791708917099171091711917129171391714917159171691717917189171991720917219172291723917249172591726917279172891729917309173191732917339173491735917369173791738917399174091741917429174391744917459174691747917489174991750917519175291753917549175591756917579175891759917609176191762917639176491765917669176791768917699177091771917729177391774917759177691777917789177991780917819178291783917849178591786917879178891789917909179191792917939179491795917969179791798917999180091801918029180391804918059180691807918089180991810918119181291813918149181591816918179181891819918209182191822918239182491825918269182791828918299183091831918329183391834918359183691837918389183991840918419184291843918449184591846918479184891849918509185191852918539185491855918569185791858918599186091861918629186391864918659186691867918689186991870918719187291873918749187591876918779187891879918809188191882918839188491885918869188791888918899189091891918929189391894918959189691897918989189991900919019190291903919049190591906919079190891909919109191191912919139191491915919169191791918919199192091921919229192391924919259192691927919289192991930919319193291933919349193591936919379193891939919409194191942919439194491945919469194791948919499195091951919529195391954919559195691957919589195991960919619196291963919649196591966919679196891969919709197191972919739197491975919769197791978919799198091981919829198391984919859198691987919889198991990919919199291993919949199591996919979199891999920009200192002920039200492005920069200792008920099201092011920129201392014920159201692017920189201992020920219202292023920249202592026920279202892029920309203192032920339203492035920369203792038920399204092041920429204392044920459204692047920489204992050920519205292053920549205592056920579205892059920609206192062920639206492065920669206792068920699207092071920729207392074920759207692077920789207992080920819208292083920849208592086920879208892089920909209192092920939209492095920969209792098920999210092101921029210392104921059210692107921089210992110921119211292113921149211592116921179211892119921209212192122921239212492125921269212792128921299213092131921329213392134921359213692137921389213992140921419214292143921449214592146921479214892149921509215192152921539215492155921569215792158921599216092161921629216392164921659216692167921689216992170921719217292173921749217592176921779217892179921809218192182921839218492185921869218792188921899219092191921929219392194921959219692197921989219992200922019220292203922049220592206922079220892209922109221192212922139221492215922169221792218922199222092221922229222392224922259222692227922289222992230922319223292233922349223592236922379223892239922409224192242922439224492245922469224792248922499225092251922529225392254922559225692257922589225992260922619226292263922649226592266922679226892269922709227192272922739227492275922769227792278922799228092281922829228392284922859228692287922889228992290922919229292293922949229592296922979229892299923009230192302923039230492305923069230792308923099231092311923129231392314923159231692317923189231992320923219232292323923249232592326923279232892329923309233192332923339233492335923369233792338923399234092341923429234392344923459234692347923489234992350923519235292353923549235592356923579235892359923609236192362923639236492365923669236792368923699237092371923729237392374923759237692377923789237992380923819238292383923849238592386923879238892389923909239192392923939239492395923969239792398923999240092401924029240392404924059240692407924089240992410924119241292413924149241592416924179241892419924209242192422924239242492425924269242792428924299243092431924329243392434924359243692437924389243992440924419244292443924449244592446924479244892449924509245192452924539245492455924569245792458924599246092461924629246392464924659246692467924689246992470924719247292473924749247592476924779247892479924809248192482924839248492485924869248792488924899249092491924929249392494924959249692497924989249992500925019250292503925049250592506925079250892509925109251192512925139251492515925169251792518925199252092521925229252392524925259252692527925289252992530925319253292533925349253592536925379253892539925409254192542925439254492545925469254792548925499255092551925529255392554925559255692557925589255992560925619256292563925649256592566925679256892569925709257192572925739257492575925769257792578925799258092581925829258392584925859258692587925889258992590925919259292593925949259592596925979259892599926009260192602926039260492605926069260792608926099261092611926129261392614926159261692617926189261992620926219262292623926249262592626926279262892629926309263192632926339263492635926369263792638926399264092641926429264392644926459264692647926489264992650926519265292653926549265592656926579265892659926609266192662926639266492665926669266792668926699267092671926729267392674926759267692677926789267992680926819268292683926849268592686926879268892689926909269192692926939269492695926969269792698926999270092701927029270392704927059270692707927089270992710927119271292713927149271592716927179271892719927209272192722927239272492725927269272792728927299273092731927329273392734927359273692737927389273992740927419274292743927449274592746927479274892749927509275192752927539275492755927569275792758927599276092761927629276392764927659276692767927689276992770927719277292773927749277592776927779277892779927809278192782927839278492785927869278792788927899279092791927929279392794927959279692797927989279992800928019280292803928049280592806928079280892809928109281192812928139281492815928169281792818928199282092821928229282392824928259282692827928289282992830928319283292833928349283592836928379283892839928409284192842928439284492845928469284792848928499285092851928529285392854928559285692857928589285992860928619286292863928649286592866928679286892869928709287192872928739287492875928769287792878928799288092881928829288392884928859288692887928889288992890928919289292893928949289592896928979289892899929009290192902929039290492905929069290792908929099291092911929129291392914929159291692917929189291992920929219292292923929249292592926929279292892929929309293192932929339293492935929369293792938929399294092941929429294392944929459294692947929489294992950929519295292953929549295592956929579295892959929609296192962929639296492965929669296792968929699297092971929729297392974929759297692977929789297992980929819298292983929849298592986929879298892989929909299192992929939299492995929969299792998929999300093001930029300393004930059300693007930089300993010930119301293013930149301593016930179301893019930209302193022930239302493025930269302793028930299303093031930329303393034930359303693037930389303993040930419304293043930449304593046930479304893049930509305193052930539305493055930569305793058930599306093061930629306393064930659306693067930689306993070930719307293073930749307593076930779307893079930809308193082930839308493085930869308793088930899309093091930929309393094930959309693097930989309993100931019310293103931049310593106931079310893109931109311193112931139311493115931169311793118931199312093121931229312393124931259312693127931289312993130931319313293133931349313593136931379313893139931409314193142931439314493145931469314793148931499315093151931529315393154931559315693157931589315993160931619316293163931649316593166931679316893169931709317193172931739317493175931769317793178931799318093181931829318393184931859318693187931889318993190931919319293193931949319593196931979319893199932009320193202932039320493205932069320793208932099321093211932129321393214932159321693217932189321993220932219322293223932249322593226932279322893229932309323193232932339323493235932369323793238932399324093241932429324393244932459324693247932489324993250932519325293253932549325593256932579325893259932609326193262932639326493265932669326793268932699327093271932729327393274932759327693277932789327993280932819328293283932849328593286932879328893289932909329193292932939329493295932969329793298932999330093301933029330393304933059330693307933089330993310933119331293313933149331593316933179331893319933209332193322933239332493325933269332793328933299333093331933329333393334933359333693337933389333993340933419334293343933449334593346933479334893349933509335193352933539335493355933569335793358933599336093361933629336393364933659336693367933689336993370933719337293373933749337593376933779337893379933809338193382933839338493385933869338793388933899339093391933929339393394933959339693397933989339993400934019340293403934049340593406934079340893409934109341193412934139341493415934169341793418934199342093421934229342393424934259342693427934289342993430934319343293433934349343593436934379343893439934409344193442934439344493445934469344793448934499345093451934529345393454934559345693457934589345993460934619346293463934649346593466934679346893469934709347193472934739347493475934769347793478934799348093481934829348393484934859348693487934889348993490934919349293493934949349593496934979349893499935009350193502935039350493505935069350793508935099351093511935129351393514935159351693517935189351993520935219352293523935249352593526935279352893529935309353193532935339353493535935369353793538935399354093541935429354393544935459354693547935489354993550935519355293553935549355593556935579355893559935609356193562935639356493565935669356793568935699357093571935729357393574935759357693577935789357993580935819358293583935849358593586935879358893589935909359193592935939359493595935969359793598935999360093601936029360393604936059360693607936089360993610936119361293613936149361593616936179361893619936209362193622936239362493625936269362793628936299363093631936329363393634936359363693637936389363993640936419364293643936449364593646936479364893649936509365193652936539365493655936569365793658936599366093661936629366393664936659366693667936689366993670936719367293673936749367593676936779367893679936809368193682936839368493685936869368793688936899369093691936929369393694936959369693697936989369993700937019370293703937049370593706937079370893709937109371193712937139371493715937169371793718937199372093721937229372393724937259372693727937289372993730937319373293733937349373593736937379373893739937409374193742937439374493745937469374793748937499375093751937529375393754937559375693757937589375993760937619376293763937649376593766937679376893769937709377193772937739377493775937769377793778937799378093781937829378393784937859378693787937889378993790937919379293793937949379593796937979379893799938009380193802938039380493805938069380793808938099381093811938129381393814938159381693817938189381993820938219382293823938249382593826938279382893829938309383193832938339383493835938369383793838938399384093841938429384393844938459384693847938489384993850938519385293853938549385593856938579385893859938609386193862938639386493865938669386793868938699387093871938729387393874938759387693877938789387993880938819388293883938849388593886938879388893889938909389193892938939389493895938969389793898938999390093901939029390393904939059390693907939089390993910939119391293913939149391593916939179391893919939209392193922939239392493925939269392793928939299393093931939329393393934939359393693937939389393993940939419394293943939449394593946939479394893949939509395193952939539395493955939569395793958939599396093961939629396393964939659396693967939689396993970939719397293973939749397593976939779397893979939809398193982939839398493985939869398793988939899399093991939929399393994939959399693997939989399994000940019400294003940049400594006940079400894009940109401194012940139401494015940169401794018940199402094021940229402394024940259402694027940289402994030940319403294033940349403594036940379403894039940409404194042940439404494045940469404794048940499405094051940529405394054940559405694057940589405994060940619406294063940649406594066940679406894069940709407194072940739407494075940769407794078940799408094081940829408394084940859408694087940889408994090940919409294093940949409594096940979409894099941009410194102941039410494105941069410794108941099411094111941129411394114941159411694117941189411994120941219412294123941249412594126941279412894129941309413194132941339413494135941369413794138941399414094141941429414394144941459414694147941489414994150941519415294153941549415594156941579415894159941609416194162941639416494165941669416794168941699417094171941729417394174941759417694177941789417994180941819418294183941849418594186941879418894189941909419194192941939419494195941969419794198941999420094201942029420394204942059420694207942089420994210942119421294213942149421594216942179421894219942209422194222942239422494225942269422794228942299423094231942329423394234942359423694237942389423994240942419424294243942449424594246942479424894249942509425194252942539425494255942569425794258942599426094261942629426394264942659426694267942689426994270942719427294273942749427594276942779427894279942809428194282942839428494285942869428794288942899429094291942929429394294942959429694297942989429994300943019430294303943049430594306943079430894309943109431194312943139431494315943169431794318943199432094321943229432394324943259432694327943289432994330943319433294333943349433594336943379433894339943409434194342943439434494345943469434794348943499435094351943529435394354943559435694357943589435994360943619436294363943649436594366943679436894369943709437194372943739437494375943769437794378943799438094381943829438394384943859438694387943889438994390943919439294393943949439594396943979439894399944009440194402944039440494405944069440794408944099441094411944129441394414944159441694417944189441994420944219442294423944249442594426944279442894429944309443194432944339443494435944369443794438944399444094441944429444394444944459444694447944489444994450944519445294453944549445594456944579445894459944609446194462944639446494465944669446794468944699447094471944729447394474944759447694477944789447994480944819448294483944849448594486944879448894489944909449194492944939449494495944969449794498944999450094501945029450394504945059450694507945089450994510945119451294513945149451594516945179451894519945209452194522945239452494525945269452794528945299453094531945329453394534945359453694537945389453994540945419454294543945449454594546945479454894549945509455194552945539455494555945569455794558945599456094561945629456394564945659456694567945689456994570945719457294573945749457594576945779457894579945809458194582945839458494585945869458794588945899459094591945929459394594945959459694597945989459994600946019460294603946049460594606946079460894609946109461194612946139461494615946169461794618946199462094621946229462394624946259462694627946289462994630946319463294633946349463594636946379463894639946409464194642946439464494645946469464794648946499465094651946529465394654946559465694657946589465994660946619466294663946649466594666946679466894669946709467194672946739467494675946769467794678946799468094681946829468394684946859468694687946889468994690946919469294693946949469594696946979469894699947009470194702947039470494705947069470794708947099471094711947129471394714947159471694717947189471994720947219472294723947249472594726947279472894729947309473194732947339473494735947369473794738947399474094741947429474394744947459474694747947489474994750947519475294753947549475594756947579475894759947609476194762947639476494765947669476794768947699477094771947729477394774947759477694777947789477994780947819478294783947849478594786947879478894789947909479194792947939479494795947969479794798947999480094801948029480394804948059480694807948089480994810948119481294813948149481594816948179481894819948209482194822948239482494825948269482794828948299483094831948329483394834948359483694837948389483994840948419484294843948449484594846948479484894849948509485194852948539485494855948569485794858948599486094861948629486394864948659486694867948689486994870948719487294873948749487594876948779487894879948809488194882948839488494885948869488794888948899489094891948929489394894948959489694897948989489994900949019490294903949049490594906949079490894909949109491194912949139491494915949169491794918949199492094921949229492394924949259492694927949289492994930949319493294933949349493594936949379493894939949409494194942949439494494945949469494794948949499495094951949529495394954949559495694957949589495994960949619496294963949649496594966949679496894969949709497194972949739497494975949769497794978949799498094981949829498394984949859498694987949889498994990949919499294993949949499594996949979499894999950009500195002950039500495005950069500795008950099501095011950129501395014950159501695017950189501995020950219502295023950249502595026950279502895029950309503195032950339503495035950369503795038950399504095041950429504395044950459504695047950489504995050950519505295053950549505595056950579505895059950609506195062950639506495065950669506795068950699507095071950729507395074950759507695077950789507995080950819508295083950849508595086950879508895089950909509195092950939509495095950969509795098950999510095101951029510395104951059510695107951089510995110951119511295113951149511595116951179511895119951209512195122951239512495125951269512795128951299513095131951329513395134951359513695137951389513995140951419514295143951449514595146951479514895149951509515195152951539515495155951569515795158951599516095161951629516395164951659516695167951689516995170951719517295173951749517595176951779517895179951809518195182951839518495185951869518795188951899519095191951929519395194951959519695197951989519995200952019520295203952049520595206952079520895209952109521195212952139521495215952169521795218952199522095221952229522395224952259522695227952289522995230952319523295233952349523595236952379523895239952409524195242952439524495245952469524795248952499525095251952529525395254952559525695257952589525995260952619526295263952649526595266952679526895269952709527195272952739527495275952769527795278952799528095281952829528395284952859528695287952889528995290952919529295293952949529595296952979529895299953009530195302953039530495305953069530795308953099531095311953129531395314953159531695317953189531995320953219532295323953249532595326953279532895329953309533195332953339533495335953369533795338953399534095341953429534395344953459534695347953489534995350953519535295353953549535595356953579535895359953609536195362953639536495365953669536795368953699537095371953729537395374953759537695377953789537995380953819538295383953849538595386953879538895389953909539195392953939539495395953969539795398953999540095401954029540395404954059540695407954089540995410954119541295413954149541595416954179541895419954209542195422954239542495425954269542795428954299543095431954329543395434954359543695437954389543995440954419544295443954449544595446954479544895449954509545195452954539545495455954569545795458954599546095461954629546395464954659546695467954689546995470954719547295473954749547595476954779547895479954809548195482954839548495485954869548795488954899549095491954929549395494954959549695497954989549995500955019550295503955049550595506955079550895509955109551195512955139551495515955169551795518955199552095521955229552395524955259552695527955289552995530955319553295533955349553595536955379553895539955409554195542955439554495545955469554795548955499555095551955529555395554955559555695557955589555995560955619556295563955649556595566955679556895569955709557195572955739557495575955769557795578955799558095581955829558395584955859558695587955889558995590955919559295593955949559595596955979559895599956009560195602956039560495605956069560795608956099561095611956129561395614956159561695617956189561995620956219562295623956249562595626956279562895629956309563195632956339563495635956369563795638956399564095641956429564395644956459564695647956489564995650956519565295653956549565595656956579565895659956609566195662956639566495665956669566795668956699567095671956729567395674956759567695677956789567995680956819568295683956849568595686956879568895689956909569195692956939569495695956969569795698956999570095701957029570395704957059570695707957089570995710957119571295713957149571595716957179571895719957209572195722957239572495725957269572795728957299573095731957329573395734957359573695737957389573995740957419574295743957449574595746957479574895749957509575195752957539575495755957569575795758957599576095761957629576395764957659576695767957689576995770957719577295773957749577595776957779577895779957809578195782957839578495785957869578795788957899579095791957929579395794957959579695797957989579995800958019580295803958049580595806958079580895809958109581195812958139581495815958169581795818958199582095821958229582395824958259582695827958289582995830958319583295833958349583595836958379583895839958409584195842958439584495845958469584795848958499585095851958529585395854958559585695857958589585995860958619586295863958649586595866958679586895869958709587195872958739587495875958769587795878958799588095881958829588395884958859588695887958889588995890958919589295893958949589595896958979589895899959009590195902959039590495905959069590795908959099591095911959129591395914959159591695917959189591995920959219592295923959249592595926959279592895929959309593195932959339593495935959369593795938959399594095941959429594395944959459594695947959489594995950959519595295953959549595595956959579595895959959609596195962959639596495965959669596795968959699597095971959729597395974959759597695977959789597995980959819598295983959849598595986959879598895989959909599195992959939599495995959969599795998959999600096001960029600396004960059600696007960089600996010960119601296013960149601596016960179601896019960209602196022960239602496025960269602796028960299603096031960329603396034960359603696037960389603996040960419604296043960449604596046960479604896049960509605196052960539605496055960569605796058960599606096061960629606396064960659606696067960689606996070960719607296073960749607596076960779607896079960809608196082960839608496085960869608796088960899609096091960929609396094960959609696097960989609996100961019610296103961049610596106961079610896109961109611196112961139611496115961169611796118961199612096121961229612396124961259612696127961289612996130961319613296133961349613596136961379613896139961409614196142961439614496145961469614796148961499615096151961529615396154961559615696157961589615996160961619616296163961649616596166961679616896169961709617196172961739617496175961769617796178961799618096181961829618396184961859618696187961889618996190961919619296193961949619596196961979619896199962009620196202962039620496205962069620796208962099621096211962129621396214962159621696217962189621996220962219622296223962249622596226962279622896229962309623196232962339623496235962369623796238962399624096241962429624396244962459624696247962489624996250962519625296253962549625596256962579625896259962609626196262962639626496265962669626796268962699627096271962729627396274962759627696277962789627996280962819628296283962849628596286962879628896289962909629196292962939629496295962969629796298962999630096301963029630396304963059630696307963089630996310963119631296313963149631596316963179631896319963209632196322963239632496325963269632796328963299633096331963329633396334963359633696337963389633996340963419634296343963449634596346963479634896349963509635196352963539635496355963569635796358963599636096361963629636396364963659636696367963689636996370963719637296373963749637596376963779637896379963809638196382963839638496385963869638796388963899639096391963929639396394963959639696397963989639996400964019640296403964049640596406964079640896409964109641196412964139641496415964169641796418964199642096421964229642396424964259642696427964289642996430964319643296433964349643596436964379643896439964409644196442964439644496445964469644796448964499645096451964529645396454964559645696457964589645996460964619646296463964649646596466964679646896469964709647196472964739647496475964769647796478964799648096481964829648396484964859648696487964889648996490964919649296493964949649596496964979649896499965009650196502965039650496505965069650796508965099651096511965129651396514965159651696517965189651996520965219652296523965249652596526965279652896529965309653196532965339653496535965369653796538965399654096541965429654396544965459654696547965489654996550965519655296553965549655596556965579655896559965609656196562965639656496565965669656796568965699657096571965729657396574965759657696577965789657996580965819658296583965849658596586965879658896589965909659196592965939659496595965969659796598965999660096601966029660396604966059660696607966089660996610966119661296613966149661596616966179661896619966209662196622966239662496625966269662796628966299663096631966329663396634966359663696637966389663996640966419664296643966449664596646966479664896649966509665196652966539665496655966569665796658966599666096661966629666396664966659666696667966689666996670966719667296673966749667596676966779667896679966809668196682966839668496685966869668796688966899669096691966929669396694966959669696697966989669996700967019670296703967049670596706967079670896709967109671196712967139671496715967169671796718967199672096721967229672396724967259672696727967289672996730967319673296733
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. (function universalModuleDefinition(root, factory) {
  4. var amdDependencies = [];
  5. var CANNON = root.CANNON;
  6. var OIMO = root.OIMO;
  7. if(typeof exports === 'object' && typeof module === 'object') {
  8. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  9. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  10. module.exports = factory(CANNON,OIMO);
  11. } else if(typeof define === 'function' && define.amd) {
  12. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  13. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  14. define("babylonjs", amdDependencies, factory);
  15. } else if(typeof exports === 'object') {
  16. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  17. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  18. exports["babylonjs"] = factory(CANNON,OIMO);
  19. } else {
  20. root["BABYLON"] = factory(CANNON,OIMO);
  21. }
  22. })(this, function(CANNON,OIMO) {
  23. CANNON = CANNON || this.CANNON;
  24. OIMO = OIMO || this.OIMO;
  25. "use strict";
  26. var BABYLON;
  27. (function (BABYLON) {
  28. /**
  29. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  30. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  31. */
  32. var EffectFallbacks = /** @class */ (function () {
  33. function EffectFallbacks() {
  34. this._defines = {};
  35. this._currentRank = 32;
  36. this._maxRank = -1;
  37. }
  38. /**
  39. * Removes the fallback from the bound mesh.
  40. */
  41. EffectFallbacks.prototype.unBindMesh = function () {
  42. this._mesh = null;
  43. };
  44. /**
  45. * Adds a fallback on the specified property.
  46. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  47. * @param define The name of the define in the shader
  48. */
  49. EffectFallbacks.prototype.addFallback = function (rank, define) {
  50. if (!this._defines[rank]) {
  51. if (rank < this._currentRank) {
  52. this._currentRank = rank;
  53. }
  54. if (rank > this._maxRank) {
  55. this._maxRank = rank;
  56. }
  57. this._defines[rank] = new Array();
  58. }
  59. this._defines[rank].push(define);
  60. };
  61. /**
  62. * Sets the mesh to use CPU skinning when needing to fallback.
  63. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  64. * @param mesh The mesh to use the fallbacks.
  65. */
  66. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  67. this._mesh = mesh;
  68. if (rank < this._currentRank) {
  69. this._currentRank = rank;
  70. }
  71. if (rank > this._maxRank) {
  72. this._maxRank = rank;
  73. }
  74. };
  75. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  76. /**
  77. * Checks to see if more fallbacks are still availible.
  78. */
  79. get: function () {
  80. return this._currentRank <= this._maxRank;
  81. },
  82. enumerable: true,
  83. configurable: true
  84. });
  85. /**
  86. * Removes the defines that shoould be removed when falling back.
  87. * @param currentDefines defines the current define statements for the shader.
  88. * @param effect defines the current effect we try to compile
  89. * @returns The resulting defines with defines of the current rank removed.
  90. */
  91. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  92. // First we try to switch to CPU skinning
  93. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  94. this._mesh.computeBonesUsingShaders = false;
  95. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  96. var scene = this._mesh.getScene();
  97. for (var index = 0; index < scene.meshes.length; index++) {
  98. var otherMesh = scene.meshes[index];
  99. if (!otherMesh.material) {
  100. continue;
  101. }
  102. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  103. continue;
  104. }
  105. if (otherMesh.material.getEffect() === effect) {
  106. otherMesh.computeBonesUsingShaders = false;
  107. }
  108. else {
  109. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  110. var subMesh = _a[_i];
  111. var subMeshEffect = subMesh.effect;
  112. if (subMeshEffect === effect) {
  113. otherMesh.computeBonesUsingShaders = false;
  114. break;
  115. }
  116. }
  117. }
  118. }
  119. }
  120. else {
  121. var currentFallbacks = this._defines[this._currentRank];
  122. if (currentFallbacks) {
  123. for (var index = 0; index < currentFallbacks.length; index++) {
  124. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  125. }
  126. }
  127. this._currentRank++;
  128. }
  129. return currentDefines;
  130. };
  131. return EffectFallbacks;
  132. }());
  133. BABYLON.EffectFallbacks = EffectFallbacks;
  134. /**
  135. * Options to be used when creating an effect.
  136. */
  137. var EffectCreationOptions = /** @class */ (function () {
  138. function EffectCreationOptions() {
  139. }
  140. return EffectCreationOptions;
  141. }());
  142. BABYLON.EffectCreationOptions = EffectCreationOptions;
  143. /**
  144. * Effect containing vertex and fragment shader that can be executed on an object.
  145. */
  146. var Effect = /** @class */ (function () {
  147. /**
  148. * Instantiates an effect.
  149. * An effect can be used to create/manage/execute vertex and fragment shaders.
  150. * @param baseName Name of the effect.
  151. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  152. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  153. * @param samplers List of sampler variables that will be passed to the shader.
  154. * @param engine Engine to be used to render the effect
  155. * @param defines Define statements to be added to the shader.
  156. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  157. * @param onCompiled Callback that will be called when the shader is compiled.
  158. * @param onError Callback that will be called if an error occurs during shader compilation.
  159. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  160. */
  161. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  162. if (samplers === void 0) { samplers = null; }
  163. if (defines === void 0) { defines = null; }
  164. if (fallbacks === void 0) { fallbacks = null; }
  165. if (onCompiled === void 0) { onCompiled = null; }
  166. if (onError === void 0) { onError = null; }
  167. var _this = this;
  168. /**
  169. * Unique ID of the effect.
  170. */
  171. this.uniqueId = 0;
  172. /**
  173. * Observable that will be called when the shader is compiled.
  174. */
  175. this.onCompileObservable = new BABYLON.Observable();
  176. /**
  177. * Observable that will be called if an error occurs during shader compilation.
  178. */
  179. this.onErrorObservable = new BABYLON.Observable();
  180. /**
  181. * Observable that will be called when effect is bound.
  182. */
  183. this.onBindObservable = new BABYLON.Observable();
  184. this._uniformBuffersNames = {};
  185. this._isReady = false;
  186. this._compilationError = "";
  187. this.name = baseName;
  188. if (attributesNamesOrOptions.attributes) {
  189. var options = attributesNamesOrOptions;
  190. this._engine = uniformsNamesOrEngine;
  191. this._attributesNames = options.attributes;
  192. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  193. this._samplers = options.samplers;
  194. this.defines = options.defines;
  195. this.onError = options.onError;
  196. this.onCompiled = options.onCompiled;
  197. this._fallbacks = options.fallbacks;
  198. this._indexParameters = options.indexParameters;
  199. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  200. if (options.uniformBuffersNames) {
  201. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  202. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  203. }
  204. }
  205. }
  206. else {
  207. this._engine = engine;
  208. this.defines = defines;
  209. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  210. this._samplers = samplers;
  211. this._attributesNames = attributesNamesOrOptions;
  212. this.onError = onError;
  213. this.onCompiled = onCompiled;
  214. this._indexParameters = indexParameters;
  215. this._fallbacks = fallbacks;
  216. }
  217. this.uniqueId = Effect._uniqueIdSeed++;
  218. var vertexSource;
  219. var fragmentSource;
  220. if (baseName.vertexElement) {
  221. vertexSource = document.getElementById(baseName.vertexElement);
  222. if (!vertexSource) {
  223. vertexSource = baseName.vertexElement;
  224. }
  225. }
  226. else {
  227. vertexSource = baseName.vertex || baseName;
  228. }
  229. if (baseName.fragmentElement) {
  230. fragmentSource = document.getElementById(baseName.fragmentElement);
  231. if (!fragmentSource) {
  232. fragmentSource = baseName.fragmentElement;
  233. }
  234. }
  235. else {
  236. fragmentSource = baseName.fragment || baseName;
  237. }
  238. this._loadVertexShader(vertexSource, function (vertexCode) {
  239. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  240. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  241. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  242. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  243. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  244. if (baseName) {
  245. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  246. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  247. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  248. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  249. }
  250. else {
  251. _this._vertexSourceCode = migratedVertexCode;
  252. _this._fragmentSourceCode = migratedFragmentCode;
  253. }
  254. _this._prepareEffect();
  255. });
  256. });
  257. });
  258. });
  259. });
  260. });
  261. }
  262. Object.defineProperty(Effect.prototype, "key", {
  263. /**
  264. * Unique key for this effect
  265. */
  266. get: function () {
  267. return this._key;
  268. },
  269. enumerable: true,
  270. configurable: true
  271. });
  272. /**
  273. * If the effect has been compiled and prepared.
  274. * @returns if the effect is compiled and prepared.
  275. */
  276. Effect.prototype.isReady = function () {
  277. return this._isReady;
  278. };
  279. /**
  280. * The engine the effect was initialized with.
  281. * @returns the engine.
  282. */
  283. Effect.prototype.getEngine = function () {
  284. return this._engine;
  285. };
  286. /**
  287. * The compiled webGL program for the effect
  288. * @returns the webGL program.
  289. */
  290. Effect.prototype.getProgram = function () {
  291. return this._program;
  292. };
  293. /**
  294. * The set of names of attribute variables for the shader.
  295. * @returns An array of attribute names.
  296. */
  297. Effect.prototype.getAttributesNames = function () {
  298. return this._attributesNames;
  299. };
  300. /**
  301. * Returns the attribute at the given index.
  302. * @param index The index of the attribute.
  303. * @returns The location of the attribute.
  304. */
  305. Effect.prototype.getAttributeLocation = function (index) {
  306. return this._attributes[index];
  307. };
  308. /**
  309. * Returns the attribute based on the name of the variable.
  310. * @param name of the attribute to look up.
  311. * @returns the attribute location.
  312. */
  313. Effect.prototype.getAttributeLocationByName = function (name) {
  314. var index = this._attributesNames.indexOf(name);
  315. return this._attributes[index];
  316. };
  317. /**
  318. * The number of attributes.
  319. * @returns the numnber of attributes.
  320. */
  321. Effect.prototype.getAttributesCount = function () {
  322. return this._attributes.length;
  323. };
  324. /**
  325. * Gets the index of a uniform variable.
  326. * @param uniformName of the uniform to look up.
  327. * @returns the index.
  328. */
  329. Effect.prototype.getUniformIndex = function (uniformName) {
  330. return this._uniformsNames.indexOf(uniformName);
  331. };
  332. /**
  333. * Returns the attribute based on the name of the variable.
  334. * @param uniformName of the uniform to look up.
  335. * @returns the location of the uniform.
  336. */
  337. Effect.prototype.getUniform = function (uniformName) {
  338. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  339. };
  340. /**
  341. * Returns an array of sampler variable names
  342. * @returns The array of sampler variable neames.
  343. */
  344. Effect.prototype.getSamplers = function () {
  345. return this._samplers;
  346. };
  347. /**
  348. * The error from the last compilation.
  349. * @returns the error string.
  350. */
  351. Effect.prototype.getCompilationError = function () {
  352. return this._compilationError;
  353. };
  354. /**
  355. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  356. * @param func The callback to be used.
  357. */
  358. Effect.prototype.executeWhenCompiled = function (func) {
  359. if (this.isReady()) {
  360. func(this);
  361. return;
  362. }
  363. this.onCompileObservable.add(function (effect) {
  364. func(effect);
  365. });
  366. };
  367. /** @ignore */
  368. Effect.prototype._loadVertexShader = function (vertex, callback) {
  369. if (BABYLON.Tools.IsWindowObjectExist()) {
  370. // DOM element ?
  371. if (vertex instanceof HTMLElement) {
  372. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  373. callback(vertexCode);
  374. return;
  375. }
  376. }
  377. // Base64 encoded ?
  378. if (vertex.substr(0, 7) === "base64:") {
  379. var vertexBinary = window.atob(vertex.substr(7));
  380. callback(vertexBinary);
  381. return;
  382. }
  383. // Is in local store ?
  384. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  385. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  386. return;
  387. }
  388. var vertexShaderUrl;
  389. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  390. vertexShaderUrl = vertex;
  391. }
  392. else {
  393. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  394. }
  395. // Vertex shader
  396. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  397. };
  398. /** @ignore */
  399. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  400. if (BABYLON.Tools.IsWindowObjectExist()) {
  401. // DOM element ?
  402. if (fragment instanceof HTMLElement) {
  403. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  404. callback(fragmentCode);
  405. return;
  406. }
  407. }
  408. // Base64 encoded ?
  409. if (fragment.substr(0, 7) === "base64:") {
  410. var fragmentBinary = window.atob(fragment.substr(7));
  411. callback(fragmentBinary);
  412. return;
  413. }
  414. // Is in local store ?
  415. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  416. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  417. return;
  418. }
  419. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  420. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  421. return;
  422. }
  423. var fragmentShaderUrl;
  424. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  425. fragmentShaderUrl = fragment;
  426. }
  427. else {
  428. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  429. }
  430. // Fragment shader
  431. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  432. };
  433. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  434. // Rebuild shaders source code
  435. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  436. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  437. vertexCode = prefix + vertexCode;
  438. fragmentCode = prefix + fragmentCode;
  439. // Number lines of shaders source code
  440. var i = 2;
  441. var regex = /\n/gm;
  442. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  443. i = 2;
  444. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  445. // Dump shaders name and formatted source code
  446. if (this.name.vertexElement) {
  447. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  448. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  449. }
  450. else if (this.name.vertex) {
  451. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  452. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  453. }
  454. else {
  455. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  456. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  457. }
  458. };
  459. ;
  460. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  461. var preparedSourceCode = this._processPrecision(sourceCode);
  462. if (this._engine.webGLVersion == 1) {
  463. callback(preparedSourceCode);
  464. return;
  465. }
  466. // Already converted
  467. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  468. callback(preparedSourceCode.replace("#version 300 es", ""));
  469. return;
  470. }
  471. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  472. // Remove extensions
  473. // #extension GL_OES_standard_derivatives : enable
  474. // #extension GL_EXT_shader_texture_lod : enable
  475. // #extension GL_EXT_frag_depth : enable
  476. // #extension GL_EXT_draw_buffers : require
  477. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  478. var result = preparedSourceCode.replace(regex, "");
  479. // Migrate to GLSL v300
  480. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  481. result = result.replace(/attribute[ \t]/g, "in ");
  482. result = result.replace(/[ \t]attribute/g, " in");
  483. if (isFragment) {
  484. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  485. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  486. result = result.replace(/texture2D\s*\(/g, "texture(");
  487. result = result.replace(/textureCube\s*\(/g, "texture(");
  488. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  489. result = result.replace(/gl_FragColor/g, "glFragColor");
  490. result = result.replace(/gl_FragData/g, "glFragData");
  491. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  492. }
  493. callback(result);
  494. };
  495. Effect.prototype._processIncludes = function (sourceCode, callback) {
  496. var _this = this;
  497. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  498. var match = regex.exec(sourceCode);
  499. var returnValue = new String(sourceCode);
  500. while (match != null) {
  501. var includeFile = match[1];
  502. // Uniform declaration
  503. if (includeFile.indexOf("__decl__") !== -1) {
  504. includeFile = includeFile.replace(/__decl__/, "");
  505. if (this._engine.supportsUniformBuffers) {
  506. includeFile = includeFile.replace(/Vertex/, "Ubo");
  507. includeFile = includeFile.replace(/Fragment/, "Ubo");
  508. }
  509. includeFile = includeFile + "Declaration";
  510. }
  511. if (Effect.IncludesShadersStore[includeFile]) {
  512. // Substitution
  513. var includeContent = Effect.IncludesShadersStore[includeFile];
  514. if (match[2]) {
  515. var splits = match[3].split(",");
  516. for (var index = 0; index < splits.length; index += 2) {
  517. var source = new RegExp(splits[index], "g");
  518. var dest = splits[index + 1];
  519. includeContent = includeContent.replace(source, dest);
  520. }
  521. }
  522. if (match[4]) {
  523. var indexString = match[5];
  524. if (indexString.indexOf("..") !== -1) {
  525. var indexSplits = indexString.split("..");
  526. var minIndex = parseInt(indexSplits[0]);
  527. var maxIndex = parseInt(indexSplits[1]);
  528. var sourceIncludeContent = includeContent.slice(0);
  529. includeContent = "";
  530. if (isNaN(maxIndex)) {
  531. maxIndex = this._indexParameters[indexSplits[1]];
  532. }
  533. for (var i = minIndex; i < maxIndex; i++) {
  534. if (!this._engine.supportsUniformBuffers) {
  535. // Ubo replacement
  536. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  537. return p1 + "{X}";
  538. });
  539. }
  540. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  541. }
  542. }
  543. else {
  544. if (!this._engine.supportsUniformBuffers) {
  545. // Ubo replacement
  546. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  547. return p1 + "{X}";
  548. });
  549. }
  550. includeContent = includeContent.replace(/\{X\}/g, indexString);
  551. }
  552. }
  553. // Replace
  554. returnValue = returnValue.replace(match[0], includeContent);
  555. }
  556. else {
  557. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  558. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  559. Effect.IncludesShadersStore[includeFile] = fileContent;
  560. _this._processIncludes(returnValue, callback);
  561. });
  562. return;
  563. }
  564. match = regex.exec(sourceCode);
  565. }
  566. callback(returnValue);
  567. };
  568. Effect.prototype._processPrecision = function (source) {
  569. if (source.indexOf("precision highp float") === -1) {
  570. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  571. source = "precision mediump float;\n" + source;
  572. }
  573. else {
  574. source = "precision highp float;\n" + source;
  575. }
  576. }
  577. else {
  578. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  579. source = source.replace("precision highp float", "precision mediump float");
  580. }
  581. }
  582. return source;
  583. };
  584. /**
  585. * Recompiles the webGL program
  586. * @param vertexSourceCode The source code for the vertex shader.
  587. * @param fragmentSourceCode The source code for the fragment shader.
  588. * @param onCompiled Callback called when completed.
  589. * @param onError Callback called on error.
  590. */
  591. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  592. var _this = this;
  593. this._isReady = false;
  594. this._vertexSourceCodeOverride = vertexSourceCode;
  595. this._fragmentSourceCodeOverride = fragmentSourceCode;
  596. this.onError = function (effect, error) {
  597. if (onError) {
  598. onError(error);
  599. }
  600. };
  601. this.onCompiled = function () {
  602. var scenes = _this.getEngine().scenes;
  603. for (var i = 0; i < scenes.length; i++) {
  604. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  605. }
  606. if (onCompiled) {
  607. onCompiled(_this._program);
  608. }
  609. };
  610. this._fallbacks = null;
  611. this._prepareEffect();
  612. };
  613. /**
  614. * Gets the uniform locations of the the specified variable names
  615. * @param names THe names of the variables to lookup.
  616. * @returns Array of locations in the same order as variable names.
  617. */
  618. Effect.prototype.getSpecificUniformLocations = function (names) {
  619. var engine = this._engine;
  620. return engine.getUniforms(this._program, names);
  621. };
  622. /**
  623. * Prepares the effect
  624. */
  625. Effect.prototype._prepareEffect = function () {
  626. var attributesNames = this._attributesNames;
  627. var defines = this.defines;
  628. var fallbacks = this._fallbacks;
  629. this._valueCache = {};
  630. var previousProgram = this._program;
  631. try {
  632. var engine = this._engine;
  633. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  634. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  635. }
  636. else {
  637. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  638. }
  639. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  640. if (engine.supportsUniformBuffers) {
  641. for (var name in this._uniformBuffersNames) {
  642. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  643. }
  644. }
  645. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  646. this._attributes = engine.getAttributes(this._program, attributesNames);
  647. var index;
  648. for (index = 0; index < this._samplers.length; index++) {
  649. var sampler = this.getUniform(this._samplers[index]);
  650. if (sampler == null) {
  651. this._samplers.splice(index, 1);
  652. index--;
  653. }
  654. }
  655. engine.bindSamplers(this);
  656. this._compilationError = "";
  657. this._isReady = true;
  658. if (this.onCompiled) {
  659. this.onCompiled(this);
  660. }
  661. this.onCompileObservable.notifyObservers(this);
  662. this.onCompileObservable.clear();
  663. // Unbind mesh reference in fallbacks
  664. if (this._fallbacks) {
  665. this._fallbacks.unBindMesh();
  666. }
  667. if (previousProgram) {
  668. this.getEngine()._deleteProgram(previousProgram);
  669. }
  670. }
  671. catch (e) {
  672. this._compilationError = e.message;
  673. // Let's go through fallbacks then
  674. BABYLON.Tools.Error("Unable to compile effect:");
  675. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  676. return " " + uniform;
  677. }));
  678. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  679. return " " + attribute;
  680. }));
  681. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  682. BABYLON.Tools.Error("Error: " + this._compilationError);
  683. if (previousProgram) {
  684. this._program = previousProgram;
  685. this._isReady = true;
  686. if (this.onError) {
  687. this.onError(this, this._compilationError);
  688. }
  689. this.onErrorObservable.notifyObservers(this);
  690. }
  691. if (fallbacks && fallbacks.isMoreFallbacks) {
  692. BABYLON.Tools.Error("Trying next fallback.");
  693. this.defines = fallbacks.reduce(this.defines, this);
  694. this._prepareEffect();
  695. }
  696. else {
  697. if (this.onError) {
  698. this.onError(this, this._compilationError);
  699. }
  700. this.onErrorObservable.notifyObservers(this);
  701. this.onErrorObservable.clear();
  702. // Unbind mesh reference in fallbacks
  703. if (this._fallbacks) {
  704. this._fallbacks.unBindMesh();
  705. }
  706. }
  707. }
  708. };
  709. Object.defineProperty(Effect.prototype, "isSupported", {
  710. /**
  711. * Checks if the effect is supported. (Must be called after compilation)
  712. */
  713. get: function () {
  714. return this._compilationError === "";
  715. },
  716. enumerable: true,
  717. configurable: true
  718. });
  719. /**
  720. * Binds a texture to the engine to be used as output of the shader.
  721. * @param channel Name of the output variable.
  722. * @param texture Texture to bind.
  723. */
  724. Effect.prototype._bindTexture = function (channel, texture) {
  725. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  726. };
  727. /**
  728. * Sets a texture on the engine to be used in the shader.
  729. * @param channel Name of the sampler variable.
  730. * @param texture Texture to set.
  731. */
  732. Effect.prototype.setTexture = function (channel, texture) {
  733. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  734. };
  735. /**
  736. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  737. * @param channel Name of the sampler variable.
  738. * @param texture Texture to set.
  739. */
  740. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  741. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  742. };
  743. /**
  744. * Sets an array of textures on the engine to be used in the shader.
  745. * @param channel Name of the variable.
  746. * @param textures Textures to set.
  747. */
  748. Effect.prototype.setTextureArray = function (channel, textures) {
  749. if (this._samplers.indexOf(channel + "Ex") === -1) {
  750. var initialPos = this._samplers.indexOf(channel);
  751. for (var index = 1; index < textures.length; index++) {
  752. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  753. }
  754. }
  755. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  756. };
  757. /**
  758. * 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)
  759. * @param channel Name of the sampler variable.
  760. * @param postProcess Post process to get the input texture from.
  761. */
  762. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  763. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  764. };
  765. /**
  766. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  767. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  768. * @param channel Name of the sampler variable.
  769. * @param postProcess Post process to get the output texture from.
  770. */
  771. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  772. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  773. };
  774. /** @ignore */
  775. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  776. var cache = this._valueCache[uniformName];
  777. var flag = matrix.updateFlag;
  778. if (cache !== undefined && cache === flag) {
  779. return false;
  780. }
  781. this._valueCache[uniformName] = flag;
  782. return true;
  783. };
  784. /** @ignore */
  785. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  786. var cache = this._valueCache[uniformName];
  787. if (!cache) {
  788. cache = [x, y];
  789. this._valueCache[uniformName] = cache;
  790. return true;
  791. }
  792. var changed = false;
  793. if (cache[0] !== x) {
  794. cache[0] = x;
  795. changed = true;
  796. }
  797. if (cache[1] !== y) {
  798. cache[1] = y;
  799. changed = true;
  800. }
  801. return changed;
  802. };
  803. /** @ignore */
  804. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  805. var cache = this._valueCache[uniformName];
  806. if (!cache) {
  807. cache = [x, y, z];
  808. this._valueCache[uniformName] = cache;
  809. return true;
  810. }
  811. var changed = false;
  812. if (cache[0] !== x) {
  813. cache[0] = x;
  814. changed = true;
  815. }
  816. if (cache[1] !== y) {
  817. cache[1] = y;
  818. changed = true;
  819. }
  820. if (cache[2] !== z) {
  821. cache[2] = z;
  822. changed = true;
  823. }
  824. return changed;
  825. };
  826. /** @ignore */
  827. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  828. var cache = this._valueCache[uniformName];
  829. if (!cache) {
  830. cache = [x, y, z, w];
  831. this._valueCache[uniformName] = cache;
  832. return true;
  833. }
  834. var changed = false;
  835. if (cache[0] !== x) {
  836. cache[0] = x;
  837. changed = true;
  838. }
  839. if (cache[1] !== y) {
  840. cache[1] = y;
  841. changed = true;
  842. }
  843. if (cache[2] !== z) {
  844. cache[2] = z;
  845. changed = true;
  846. }
  847. if (cache[3] !== w) {
  848. cache[3] = w;
  849. changed = true;
  850. }
  851. return changed;
  852. };
  853. /**
  854. * Binds a buffer to a uniform.
  855. * @param buffer Buffer to bind.
  856. * @param name Name of the uniform variable to bind to.
  857. */
  858. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  859. var bufferName = this._uniformBuffersNames[name];
  860. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  861. return;
  862. }
  863. Effect._baseCache[bufferName] = buffer;
  864. this._engine.bindUniformBufferBase(buffer, bufferName);
  865. };
  866. /**
  867. * Binds block to a uniform.
  868. * @param blockName Name of the block to bind.
  869. * @param index Index to bind.
  870. */
  871. Effect.prototype.bindUniformBlock = function (blockName, index) {
  872. this._engine.bindUniformBlock(this._program, blockName, index);
  873. };
  874. /**
  875. * Sets an interger value on a uniform variable.
  876. * @param uniformName Name of the variable.
  877. * @param value Value to be set.
  878. * @returns this effect.
  879. */
  880. Effect.prototype.setInt = function (uniformName, value) {
  881. var cache = this._valueCache[uniformName];
  882. if (cache !== undefined && cache === value)
  883. return this;
  884. this._valueCache[uniformName] = value;
  885. this._engine.setInt(this.getUniform(uniformName), value);
  886. return this;
  887. };
  888. /**
  889. * Sets an int array on a uniform variable.
  890. * @param uniformName Name of the variable.
  891. * @param array array to be set.
  892. * @returns this effect.
  893. */
  894. Effect.prototype.setIntArray = function (uniformName, array) {
  895. this._valueCache[uniformName] = null;
  896. this._engine.setIntArray(this.getUniform(uniformName), array);
  897. return this;
  898. };
  899. /**
  900. * 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)
  901. * @param uniformName Name of the variable.
  902. * @param array array to be set.
  903. * @returns this effect.
  904. */
  905. Effect.prototype.setIntArray2 = function (uniformName, array) {
  906. this._valueCache[uniformName] = null;
  907. this._engine.setIntArray2(this.getUniform(uniformName), array);
  908. return this;
  909. };
  910. /**
  911. * 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)
  912. * @param uniformName Name of the variable.
  913. * @param array array to be set.
  914. * @returns this effect.
  915. */
  916. Effect.prototype.setIntArray3 = function (uniformName, array) {
  917. this._valueCache[uniformName] = null;
  918. this._engine.setIntArray3(this.getUniform(uniformName), array);
  919. return this;
  920. };
  921. /**
  922. * 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)
  923. * @param uniformName Name of the variable.
  924. * @param array array to be set.
  925. * @returns this effect.
  926. */
  927. Effect.prototype.setIntArray4 = function (uniformName, array) {
  928. this._valueCache[uniformName] = null;
  929. this._engine.setIntArray4(this.getUniform(uniformName), array);
  930. return this;
  931. };
  932. /**
  933. * Sets an float array on a uniform variable.
  934. * @param uniformName Name of the variable.
  935. * @param array array to be set.
  936. * @returns this effect.
  937. */
  938. Effect.prototype.setFloatArray = function (uniformName, array) {
  939. this._valueCache[uniformName] = null;
  940. this._engine.setFloatArray(this.getUniform(uniformName), array);
  941. return this;
  942. };
  943. /**
  944. * 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)
  945. * @param uniformName Name of the variable.
  946. * @param array array to be set.
  947. * @returns this effect.
  948. */
  949. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  950. this._valueCache[uniformName] = null;
  951. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  952. return this;
  953. };
  954. /**
  955. * 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)
  956. * @param uniformName Name of the variable.
  957. * @param array array to be set.
  958. * @returns this effect.
  959. */
  960. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  961. this._valueCache[uniformName] = null;
  962. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  963. return this;
  964. };
  965. /**
  966. * 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)
  967. * @param uniformName Name of the variable.
  968. * @param array array to be set.
  969. * @returns this effect.
  970. */
  971. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  972. this._valueCache[uniformName] = null;
  973. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  974. return this;
  975. };
  976. /**
  977. * Sets an array on a uniform variable.
  978. * @param uniformName Name of the variable.
  979. * @param array array to be set.
  980. * @returns this effect.
  981. */
  982. Effect.prototype.setArray = function (uniformName, array) {
  983. this._valueCache[uniformName] = null;
  984. this._engine.setArray(this.getUniform(uniformName), array);
  985. return this;
  986. };
  987. /**
  988. * 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)
  989. * @param uniformName Name of the variable.
  990. * @param array array to be set.
  991. * @returns this effect.
  992. */
  993. Effect.prototype.setArray2 = function (uniformName, array) {
  994. this._valueCache[uniformName] = null;
  995. this._engine.setArray2(this.getUniform(uniformName), array);
  996. return this;
  997. };
  998. /**
  999. * 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)
  1000. * @param uniformName Name of the variable.
  1001. * @param array array to be set.
  1002. * @returns this effect.
  1003. */
  1004. Effect.prototype.setArray3 = function (uniformName, array) {
  1005. this._valueCache[uniformName] = null;
  1006. this._engine.setArray3(this.getUniform(uniformName), array);
  1007. return this;
  1008. };
  1009. /**
  1010. * 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)
  1011. * @param uniformName Name of the variable.
  1012. * @param array array to be set.
  1013. * @returns this effect.
  1014. */
  1015. Effect.prototype.setArray4 = function (uniformName, array) {
  1016. this._valueCache[uniformName] = null;
  1017. this._engine.setArray4(this.getUniform(uniformName), array);
  1018. return this;
  1019. };
  1020. /**
  1021. * Sets matrices on a uniform variable.
  1022. * @param uniformName Name of the variable.
  1023. * @param matrices matrices to be set.
  1024. * @returns this effect.
  1025. */
  1026. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1027. if (!matrices) {
  1028. return this;
  1029. }
  1030. this._valueCache[uniformName] = null;
  1031. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1032. return this;
  1033. };
  1034. /**
  1035. * Sets matrix on a uniform variable.
  1036. * @param uniformName Name of the variable.
  1037. * @param matrix matrix to be set.
  1038. * @returns this effect.
  1039. */
  1040. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1041. if (this._cacheMatrix(uniformName, matrix)) {
  1042. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1043. }
  1044. return this;
  1045. };
  1046. /**
  1047. * 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)
  1048. * @param uniformName Name of the variable.
  1049. * @param matrix matrix to be set.
  1050. * @returns this effect.
  1051. */
  1052. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1053. this._valueCache[uniformName] = null;
  1054. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1055. return this;
  1056. };
  1057. /**
  1058. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1059. * @param uniformName Name of the variable.
  1060. * @param matrix matrix to be set.
  1061. * @returns this effect.
  1062. */
  1063. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1064. this._valueCache[uniformName] = null;
  1065. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1066. return this;
  1067. };
  1068. /**
  1069. * Sets a float on a uniform variable.
  1070. * @param uniformName Name of the variable.
  1071. * @param value value to be set.
  1072. * @returns this effect.
  1073. */
  1074. Effect.prototype.setFloat = function (uniformName, value) {
  1075. var cache = this._valueCache[uniformName];
  1076. if (cache !== undefined && cache === value)
  1077. return this;
  1078. this._valueCache[uniformName] = value;
  1079. this._engine.setFloat(this.getUniform(uniformName), value);
  1080. return this;
  1081. };
  1082. /**
  1083. * Sets a boolean on a uniform variable.
  1084. * @param uniformName Name of the variable.
  1085. * @param bool value to be set.
  1086. * @returns this effect.
  1087. */
  1088. Effect.prototype.setBool = function (uniformName, bool) {
  1089. var cache = this._valueCache[uniformName];
  1090. if (cache !== undefined && cache === bool)
  1091. return this;
  1092. this._valueCache[uniformName] = bool;
  1093. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1094. return this;
  1095. };
  1096. /**
  1097. * Sets a Vector2 on a uniform variable.
  1098. * @param uniformName Name of the variable.
  1099. * @param vector2 vector2 to be set.
  1100. * @returns this effect.
  1101. */
  1102. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1103. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1104. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1105. }
  1106. return this;
  1107. };
  1108. /**
  1109. * Sets a float2 on a uniform variable.
  1110. * @param uniformName Name of the variable.
  1111. * @param x First float in float2.
  1112. * @param y Second float in float2.
  1113. * @returns this effect.
  1114. */
  1115. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1116. if (this._cacheFloat2(uniformName, x, y)) {
  1117. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1118. }
  1119. return this;
  1120. };
  1121. /**
  1122. * Sets a Vector3 on a uniform variable.
  1123. * @param uniformName Name of the variable.
  1124. * @param vector3 Value to be set.
  1125. * @returns this effect.
  1126. */
  1127. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1128. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1129. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1130. }
  1131. return this;
  1132. };
  1133. /**
  1134. * Sets a float3 on a uniform variable.
  1135. * @param uniformName Name of the variable.
  1136. * @param x First float in float3.
  1137. * @param y Second float in float3.
  1138. * @param z Third float in float3.
  1139. * @returns this effect.
  1140. */
  1141. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1142. if (this._cacheFloat3(uniformName, x, y, z)) {
  1143. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1144. }
  1145. return this;
  1146. };
  1147. /**
  1148. * Sets a Vector4 on a uniform variable.
  1149. * @param uniformName Name of the variable.
  1150. * @param vector4 Value to be set.
  1151. * @returns this effect.
  1152. */
  1153. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1154. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1155. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1156. }
  1157. return this;
  1158. };
  1159. /**
  1160. * Sets a float4 on a uniform variable.
  1161. * @param uniformName Name of the variable.
  1162. * @param x First float in float4.
  1163. * @param y Second float in float4.
  1164. * @param z Third float in float4.
  1165. * @param w Fourth float in float4.
  1166. * @returns this effect.
  1167. */
  1168. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1169. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1170. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1171. }
  1172. return this;
  1173. };
  1174. /**
  1175. * Sets a Color3 on a uniform variable.
  1176. * @param uniformName Name of the variable.
  1177. * @param color3 Value to be set.
  1178. * @returns this effect.
  1179. */
  1180. Effect.prototype.setColor3 = function (uniformName, color3) {
  1181. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1182. this._engine.setColor3(this.getUniform(uniformName), color3);
  1183. }
  1184. return this;
  1185. };
  1186. /**
  1187. * Sets a Color4 on a uniform variable.
  1188. * @param uniformName Name of the variable.
  1189. * @param color3 Value to be set.
  1190. * @param alpha Alpha value to be set.
  1191. * @returns this effect.
  1192. */
  1193. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1194. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1195. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1196. }
  1197. return this;
  1198. };
  1199. /**
  1200. * Sets a Color4 on a uniform variable
  1201. * @param uniformName defines the name of the variable
  1202. * @param color4 defines the value to be set
  1203. * @returns this effect.
  1204. */
  1205. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1206. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1207. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1208. }
  1209. return this;
  1210. };
  1211. /**
  1212. * Resets the cache of effects.
  1213. */
  1214. Effect.ResetCache = function () {
  1215. Effect._baseCache = {};
  1216. };
  1217. Effect._uniqueIdSeed = 0;
  1218. Effect._baseCache = {};
  1219. /**
  1220. * Store of each shader (The can be looked up using effect.key)
  1221. */
  1222. Effect.ShadersStore = {};
  1223. /**
  1224. * Store of each included file for a shader (The can be looked up using effect.key)
  1225. */
  1226. Effect.IncludesShadersStore = {};
  1227. return Effect;
  1228. }());
  1229. BABYLON.Effect = Effect;
  1230. })(BABYLON || (BABYLON = {}));
  1231. //# sourceMappingURL=babylon.effect.js.map
  1232. "use strict";
  1233. //# sourceMappingURL=babylon.types.js.map
  1234. "use strict";
  1235. var BABYLON;
  1236. (function (BABYLON) {
  1237. var KeyboardEventTypes = /** @class */ (function () {
  1238. function KeyboardEventTypes() {
  1239. }
  1240. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1241. get: function () {
  1242. return KeyboardEventTypes._KEYDOWN;
  1243. },
  1244. enumerable: true,
  1245. configurable: true
  1246. });
  1247. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1248. get: function () {
  1249. return KeyboardEventTypes._KEYUP;
  1250. },
  1251. enumerable: true,
  1252. configurable: true
  1253. });
  1254. KeyboardEventTypes._KEYDOWN = 0x01;
  1255. KeyboardEventTypes._KEYUP = 0x02;
  1256. return KeyboardEventTypes;
  1257. }());
  1258. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1259. var KeyboardInfo = /** @class */ (function () {
  1260. function KeyboardInfo(type, event) {
  1261. this.type = type;
  1262. this.event = event;
  1263. }
  1264. return KeyboardInfo;
  1265. }());
  1266. BABYLON.KeyboardInfo = KeyboardInfo;
  1267. /**
  1268. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1269. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1270. */
  1271. var KeyboardInfoPre = /** @class */ (function (_super) {
  1272. __extends(KeyboardInfoPre, _super);
  1273. function KeyboardInfoPre(type, event) {
  1274. var _this = _super.call(this, type, event) || this;
  1275. _this.skipOnPointerObservable = false;
  1276. return _this;
  1277. }
  1278. return KeyboardInfoPre;
  1279. }(KeyboardInfo));
  1280. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1281. })(BABYLON || (BABYLON = {}));
  1282. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1283. "use strict";
  1284. var BABYLON;
  1285. (function (BABYLON) {
  1286. var PointerEventTypes = /** @class */ (function () {
  1287. function PointerEventTypes() {
  1288. }
  1289. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1290. get: function () {
  1291. return PointerEventTypes._POINTERDOWN;
  1292. },
  1293. enumerable: true,
  1294. configurable: true
  1295. });
  1296. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1297. get: function () {
  1298. return PointerEventTypes._POINTERUP;
  1299. },
  1300. enumerable: true,
  1301. configurable: true
  1302. });
  1303. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1304. get: function () {
  1305. return PointerEventTypes._POINTERMOVE;
  1306. },
  1307. enumerable: true,
  1308. configurable: true
  1309. });
  1310. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1311. get: function () {
  1312. return PointerEventTypes._POINTERWHEEL;
  1313. },
  1314. enumerable: true,
  1315. configurable: true
  1316. });
  1317. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1318. get: function () {
  1319. return PointerEventTypes._POINTERPICK;
  1320. },
  1321. enumerable: true,
  1322. configurable: true
  1323. });
  1324. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1325. get: function () {
  1326. return PointerEventTypes._POINTERTAP;
  1327. },
  1328. enumerable: true,
  1329. configurable: true
  1330. });
  1331. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1332. get: function () {
  1333. return PointerEventTypes._POINTERDOUBLETAP;
  1334. },
  1335. enumerable: true,
  1336. configurable: true
  1337. });
  1338. PointerEventTypes._POINTERDOWN = 0x01;
  1339. PointerEventTypes._POINTERUP = 0x02;
  1340. PointerEventTypes._POINTERMOVE = 0x04;
  1341. PointerEventTypes._POINTERWHEEL = 0x08;
  1342. PointerEventTypes._POINTERPICK = 0x10;
  1343. PointerEventTypes._POINTERTAP = 0x20;
  1344. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1345. return PointerEventTypes;
  1346. }());
  1347. BABYLON.PointerEventTypes = PointerEventTypes;
  1348. var PointerInfoBase = /** @class */ (function () {
  1349. function PointerInfoBase(type, event) {
  1350. this.type = type;
  1351. this.event = event;
  1352. }
  1353. return PointerInfoBase;
  1354. }());
  1355. BABYLON.PointerInfoBase = PointerInfoBase;
  1356. /**
  1357. * This class is used to store pointer related info for the onPrePointerObservable event.
  1358. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1359. */
  1360. var PointerInfoPre = /** @class */ (function (_super) {
  1361. __extends(PointerInfoPre, _super);
  1362. function PointerInfoPre(type, event, localX, localY) {
  1363. var _this = _super.call(this, type, event) || this;
  1364. _this.skipOnPointerObservable = false;
  1365. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1366. return _this;
  1367. }
  1368. return PointerInfoPre;
  1369. }(PointerInfoBase));
  1370. BABYLON.PointerInfoPre = PointerInfoPre;
  1371. /**
  1372. * This type contains all the data related to a pointer event in Babylon.js.
  1373. * 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.
  1374. */
  1375. var PointerInfo = /** @class */ (function (_super) {
  1376. __extends(PointerInfo, _super);
  1377. function PointerInfo(type, event, pickInfo) {
  1378. var _this = _super.call(this, type, event) || this;
  1379. _this.pickInfo = pickInfo;
  1380. return _this;
  1381. }
  1382. return PointerInfo;
  1383. }(PointerInfoBase));
  1384. BABYLON.PointerInfo = PointerInfo;
  1385. })(BABYLON || (BABYLON = {}));
  1386. //# sourceMappingURL=babylon.pointerEvents.js.map
  1387. "use strict";
  1388. var BABYLON;
  1389. (function (BABYLON) {
  1390. BABYLON.ToGammaSpace = 1 / 2.2;
  1391. BABYLON.ToLinearSpace = 2.2;
  1392. BABYLON.Epsilon = 0.001;
  1393. /**
  1394. * Class used to hold a RBG color
  1395. */
  1396. var Color3 = /** @class */ (function () {
  1397. /**
  1398. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1399. * @param r defines the red component (between 0 and 1, default is 0)
  1400. * @param g defines the green component (between 0 and 1, default is 0)
  1401. * @param b defines the blue component (between 0 and 1, default is 0)
  1402. */
  1403. function Color3(
  1404. /**
  1405. * Defines the red component (between 0 and 1, default is 0)
  1406. */
  1407. r,
  1408. /**
  1409. * Defines the green component (between 0 and 1, default is 0)
  1410. */
  1411. g,
  1412. /**
  1413. * Defines the blue component (between 0 and 1, default is 0)
  1414. */
  1415. b) {
  1416. if (r === void 0) { r = 0; }
  1417. if (g === void 0) { g = 0; }
  1418. if (b === void 0) { b = 0; }
  1419. this.r = r;
  1420. this.g = g;
  1421. this.b = b;
  1422. }
  1423. /**
  1424. * Creates a string with the Color3 current values
  1425. * @returns the string representation of the Color3 object
  1426. */
  1427. Color3.prototype.toString = function () {
  1428. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1429. };
  1430. /**
  1431. * Returns the string "Color3"
  1432. * @returns "Color3"
  1433. */
  1434. Color3.prototype.getClassName = function () {
  1435. return "Color3";
  1436. };
  1437. /**
  1438. * Compute the Color3 hash code
  1439. * @returns an unique number that can be used to hash Color3 objects
  1440. */
  1441. Color3.prototype.getHashCode = function () {
  1442. var hash = this.r || 0;
  1443. hash = (hash * 397) ^ (this.g || 0);
  1444. hash = (hash * 397) ^ (this.b || 0);
  1445. return hash;
  1446. };
  1447. // Operators
  1448. /**
  1449. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1450. * @param array defines the array where to store the r,g,b components
  1451. * @param index defines an optional index in the target array to define where to start storing values
  1452. * @returns the current Color3 object
  1453. */
  1454. Color3.prototype.toArray = function (array, index) {
  1455. if (index === undefined) {
  1456. index = 0;
  1457. }
  1458. array[index] = this.r;
  1459. array[index + 1] = this.g;
  1460. array[index + 2] = this.b;
  1461. return this;
  1462. };
  1463. /**
  1464. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1465. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1466. * @returns a new {BABYLON.Color4} object
  1467. */
  1468. Color3.prototype.toColor4 = function (alpha) {
  1469. if (alpha === void 0) { alpha = 1; }
  1470. return new Color4(this.r, this.g, this.b, alpha);
  1471. };
  1472. /**
  1473. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1474. * @returns the new array
  1475. */
  1476. Color3.prototype.asArray = function () {
  1477. var result = new Array();
  1478. this.toArray(result, 0);
  1479. return result;
  1480. };
  1481. /**
  1482. * Returns the luminance value
  1483. * @returns a float value
  1484. */
  1485. Color3.prototype.toLuminance = function () {
  1486. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1487. };
  1488. /**
  1489. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1490. * @param otherColor defines the second operand
  1491. * @returns the new Color3 object
  1492. */
  1493. Color3.prototype.multiply = function (otherColor) {
  1494. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1495. };
  1496. /**
  1497. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1498. * @param otherColor defines the second operand
  1499. * @param result defines the Color3 object where to store the result
  1500. * @returns the current Color3
  1501. */
  1502. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1503. result.r = this.r * otherColor.r;
  1504. result.g = this.g * otherColor.g;
  1505. result.b = this.b * otherColor.b;
  1506. return this;
  1507. };
  1508. /**
  1509. * Determines equality between Color3 objects
  1510. * @param otherColor defines the second operand
  1511. * @returns true if the rgb values are equal to the passed ones
  1512. */
  1513. Color3.prototype.equals = function (otherColor) {
  1514. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1515. };
  1516. /**
  1517. * Determines equality between the current Color3 object and a set of r,b,g values
  1518. * @param r defines the red component to check
  1519. * @param g defines the green component to check
  1520. * @param b defines the blue component to check
  1521. * @returns true if the rgb values are equal to the passed ones
  1522. */
  1523. Color3.prototype.equalsFloats = function (r, g, b) {
  1524. return this.r === r && this.g === g && this.b === b;
  1525. };
  1526. /**
  1527. * Multiplies in place each rgb value by scale
  1528. * @param scale defines the scaling factor
  1529. * @returns the updated Color3
  1530. */
  1531. Color3.prototype.scale = function (scale) {
  1532. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1533. };
  1534. /**
  1535. * Multiplies the rgb values by scale and stores the result into "result"
  1536. * @param scale defines the scaling factor
  1537. * @param result defines the Color3 object where to store the result
  1538. * @returns the unmodified current Color3
  1539. */
  1540. Color3.prototype.scaleToRef = function (scale, result) {
  1541. result.r = this.r * scale;
  1542. result.g = this.g * scale;
  1543. result.b = this.b * scale;
  1544. return this;
  1545. };
  1546. /**
  1547. * Scale the current Color3 values by a factor and add the result to a given Color3
  1548. * @param scale defines the scale factor
  1549. * @param result defines color to store the result into
  1550. * @returns the unmodified current Color3
  1551. */
  1552. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1553. result.r += this.r * scale;
  1554. result.g += this.g * scale;
  1555. result.b += this.b * scale;
  1556. return this;
  1557. };
  1558. /**
  1559. * Clamps the rgb values by the min and max values and stores the result into "result"
  1560. * @param min defines minimum clamping value (default is 0)
  1561. * @param max defines maximum clamping value (default is 1)
  1562. * @param result defines color to store the result into
  1563. * @returns the original Color3
  1564. */
  1565. Color3.prototype.clampToRef = function (min, max, result) {
  1566. if (min === void 0) { min = 0; }
  1567. if (max === void 0) { max = 1; }
  1568. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1569. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1570. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1571. return this;
  1572. };
  1573. /**
  1574. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1575. * @param otherColor defines the second operand
  1576. * @returns the new Color3
  1577. */
  1578. Color3.prototype.add = function (otherColor) {
  1579. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1580. };
  1581. /**
  1582. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1583. * @param otherColor defines the second operand
  1584. * @param result defines Color3 object to store the result into
  1585. * @returns the unmodified current Color3
  1586. */
  1587. Color3.prototype.addToRef = function (otherColor, result) {
  1588. result.r = this.r + otherColor.r;
  1589. result.g = this.g + otherColor.g;
  1590. result.b = this.b + otherColor.b;
  1591. return this;
  1592. };
  1593. /**
  1594. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1595. * @param otherColor defines the second operand
  1596. * @returns the new Color3
  1597. */
  1598. Color3.prototype.subtract = function (otherColor) {
  1599. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1600. };
  1601. /**
  1602. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1603. * @param otherColor defines the second operand
  1604. * @param result defines Color3 object to store the result into
  1605. * @returns the unmodified current Color3
  1606. */
  1607. Color3.prototype.subtractToRef = function (otherColor, result) {
  1608. result.r = this.r - otherColor.r;
  1609. result.g = this.g - otherColor.g;
  1610. result.b = this.b - otherColor.b;
  1611. return this;
  1612. };
  1613. /**
  1614. * Copy the current object
  1615. * @returns a new Color3 copied the current one
  1616. */
  1617. Color3.prototype.clone = function () {
  1618. return new Color3(this.r, this.g, this.b);
  1619. };
  1620. /**
  1621. * Copies the rgb values from the source in the current Color3
  1622. * @param source defines the source Color3 object
  1623. * @returns the updated Color3 object
  1624. */
  1625. Color3.prototype.copyFrom = function (source) {
  1626. this.r = source.r;
  1627. this.g = source.g;
  1628. this.b = source.b;
  1629. return this;
  1630. };
  1631. /**
  1632. * Updates the Color3 rgb values from the passed floats
  1633. * @param r defines the red component to read from
  1634. * @param g defines the green component to read from
  1635. * @param b defines the blue component to read from
  1636. * @returns the current Color3 object
  1637. */
  1638. Color3.prototype.copyFromFloats = function (r, g, b) {
  1639. this.r = r;
  1640. this.g = g;
  1641. this.b = b;
  1642. return this;
  1643. };
  1644. /**
  1645. * Updates the Color3 rgb values from the passed floats
  1646. * @param r defines the red component to read from
  1647. * @param g defines the green component to read from
  1648. * @param b defines the blue component to read from
  1649. * @returns the current Color3 object
  1650. */
  1651. Color3.prototype.set = function (r, g, b) {
  1652. return this.copyFromFloats(r, g, b);
  1653. };
  1654. /**
  1655. * Compute the Color3 hexadecimal code as a string
  1656. * @returns a string containing the hexadecimal representation of the Color3 object
  1657. */
  1658. Color3.prototype.toHexString = function () {
  1659. var intR = (this.r * 255) | 0;
  1660. var intG = (this.g * 255) | 0;
  1661. var intB = (this.b * 255) | 0;
  1662. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1663. };
  1664. /**
  1665. * Computes a new Color3 converted from the current one to linear space
  1666. * @returns a new Color3 object
  1667. */
  1668. Color3.prototype.toLinearSpace = function () {
  1669. var convertedColor = new Color3();
  1670. this.toLinearSpaceToRef(convertedColor);
  1671. return convertedColor;
  1672. };
  1673. /**
  1674. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1675. * @param convertedColor defines the Color3 object where to store the linear space version
  1676. * @returns the unmodified Color3
  1677. */
  1678. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1679. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1680. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1681. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1682. return this;
  1683. };
  1684. /**
  1685. * Computes a new Color3 converted from the current one to gamma space
  1686. * @returns a new Color3 object
  1687. */
  1688. Color3.prototype.toGammaSpace = function () {
  1689. var convertedColor = new Color3();
  1690. this.toGammaSpaceToRef(convertedColor);
  1691. return convertedColor;
  1692. };
  1693. /**
  1694. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1695. * @param convertedColor defines the Color3 object where to store the gamma space version
  1696. * @returns the unmodified Color3
  1697. */
  1698. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1699. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1700. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1701. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1702. return this;
  1703. };
  1704. // Statics
  1705. /**
  1706. * Creates a new Color3 from the string containing valid hexadecimal values
  1707. * @param hex defines a string containing valid hexadecimal values
  1708. * @returns a new Color3 object
  1709. */
  1710. Color3.FromHexString = function (hex) {
  1711. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1712. return new Color3(0, 0, 0);
  1713. }
  1714. var r = parseInt(hex.substring(1, 3), 16);
  1715. var g = parseInt(hex.substring(3, 5), 16);
  1716. var b = parseInt(hex.substring(5, 7), 16);
  1717. return Color3.FromInts(r, g, b);
  1718. };
  1719. /**
  1720. * Creates a new Vector3 from the starting index of the passed array
  1721. * @param array defines the source array
  1722. * @param offset defines an offset in the source array
  1723. * @returns a new Color3 object
  1724. */
  1725. Color3.FromArray = function (array, offset) {
  1726. if (offset === void 0) { offset = 0; }
  1727. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1728. };
  1729. /**
  1730. * Creates a new Color3 from integer values (< 256)
  1731. * @param r defines the red component to read from (value between 0 and 255)
  1732. * @param g defines the green component to read from (value between 0 and 255)
  1733. * @param b defines the blue component to read from (value between 0 and 255)
  1734. * @returns a new Color3 object
  1735. */
  1736. Color3.FromInts = function (r, g, b) {
  1737. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1738. };
  1739. /**
  1740. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1741. * @param start defines the start Color3 value
  1742. * @param end defines the end Color3 value
  1743. * @param amount defines the gradient value between start and end
  1744. * @returns a new Color3 object
  1745. */
  1746. Color3.Lerp = function (start, end, amount) {
  1747. var r = start.r + ((end.r - start.r) * amount);
  1748. var g = start.g + ((end.g - start.g) * amount);
  1749. var b = start.b + ((end.b - start.b) * amount);
  1750. return new Color3(r, g, b);
  1751. };
  1752. /**
  1753. * Returns a Color3 value containing a red color
  1754. * @returns a new Color3 object
  1755. */
  1756. Color3.Red = function () { return new Color3(1, 0, 0); };
  1757. /**
  1758. * Returns a Color3 value containing a green color
  1759. * @returns a new Color3 object
  1760. */
  1761. Color3.Green = function () { return new Color3(0, 1, 0); };
  1762. /**
  1763. * Returns a Color3 value containing a blue color
  1764. * @returns a new Color3 object
  1765. */
  1766. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1767. /**
  1768. * Returns a Color3 value containing a black color
  1769. * @returns a new Color3 object
  1770. */
  1771. Color3.Black = function () { return new Color3(0, 0, 0); };
  1772. /**
  1773. * Returns a Color3 value containing a white color
  1774. * @returns a new Color3 object
  1775. */
  1776. Color3.White = function () { return new Color3(1, 1, 1); };
  1777. /**
  1778. * Returns a Color3 value containing a purple color
  1779. * @returns a new Color3 object
  1780. */
  1781. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1782. /**
  1783. * Returns a Color3 value containing a magenta color
  1784. * @returns a new Color3 object
  1785. */
  1786. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1787. /**
  1788. * Returns a Color3 value containing a yellow color
  1789. * @returns a new Color3 object
  1790. */
  1791. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1792. /**
  1793. * Returns a Color3 value containing a gray color
  1794. * @returns a new Color3 object
  1795. */
  1796. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1797. /**
  1798. * Returns a Color3 value containing a teal color
  1799. * @returns a new Color3 object
  1800. */
  1801. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1802. /**
  1803. * Returns a Color3 value containing a random color
  1804. * @returns a new Color3 object
  1805. */
  1806. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1807. return Color3;
  1808. }());
  1809. BABYLON.Color3 = Color3;
  1810. /**
  1811. * Class used to hold a RBGA color
  1812. */
  1813. var Color4 = /** @class */ (function () {
  1814. /**
  1815. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1816. * @param r defines the red component (between 0 and 1, default is 0)
  1817. * @param g defines the green component (between 0 and 1, default is 0)
  1818. * @param b defines the blue component (between 0 and 1, default is 0)
  1819. * @param a defines the alpha component (between 0 and 1, default is 1)
  1820. */
  1821. function Color4(
  1822. /**
  1823. * Defines the red component (between 0 and 1, default is 0)
  1824. */
  1825. r,
  1826. /**
  1827. * Defines the green component (between 0 and 1, default is 0)
  1828. */
  1829. g,
  1830. /**
  1831. * Defines the blue component (between 0 and 1, default is 0)
  1832. */
  1833. b,
  1834. /**
  1835. * Defines the alpha component (between 0 and 1, default is 1)
  1836. */
  1837. a) {
  1838. if (r === void 0) { r = 0; }
  1839. if (g === void 0) { g = 0; }
  1840. if (b === void 0) { b = 0; }
  1841. if (a === void 0) { a = 1; }
  1842. this.r = r;
  1843. this.g = g;
  1844. this.b = b;
  1845. this.a = a;
  1846. }
  1847. // Operators
  1848. /**
  1849. * Adds in place the passed Color4 values to the current Color4 object
  1850. * @param right defines the second operand
  1851. * @returns the current updated Color4 object
  1852. */
  1853. Color4.prototype.addInPlace = function (right) {
  1854. this.r += right.r;
  1855. this.g += right.g;
  1856. this.b += right.b;
  1857. this.a += right.a;
  1858. return this;
  1859. };
  1860. /**
  1861. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1862. * @returns the new array
  1863. */
  1864. Color4.prototype.asArray = function () {
  1865. var result = new Array();
  1866. this.toArray(result, 0);
  1867. return result;
  1868. };
  1869. /**
  1870. * Stores from the starting index in the passed array the Color4 successive values
  1871. * @param array defines the array where to store the r,g,b components
  1872. * @param index defines an optional index in the target array to define where to start storing values
  1873. * @returns the current Color4 object
  1874. */
  1875. Color4.prototype.toArray = function (array, index) {
  1876. if (index === undefined) {
  1877. index = 0;
  1878. }
  1879. array[index] = this.r;
  1880. array[index + 1] = this.g;
  1881. array[index + 2] = this.b;
  1882. array[index + 3] = this.a;
  1883. return this;
  1884. };
  1885. /**
  1886. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1887. * @param right defines the second operand
  1888. * @returns a new Color4 object
  1889. */
  1890. Color4.prototype.add = function (right) {
  1891. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1892. };
  1893. /**
  1894. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1895. * @param right defines the second operand
  1896. * @returns a new Color4 object
  1897. */
  1898. Color4.prototype.subtract = function (right) {
  1899. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1900. };
  1901. /**
  1902. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1903. * @param right defines the second operand
  1904. * @param result defines the Color4 object where to store the result
  1905. * @returns the current Color4 object
  1906. */
  1907. Color4.prototype.subtractToRef = function (right, result) {
  1908. result.r = this.r - right.r;
  1909. result.g = this.g - right.g;
  1910. result.b = this.b - right.b;
  1911. result.a = this.a - right.a;
  1912. return this;
  1913. };
  1914. /**
  1915. * Creates a new Color4 with the current Color4 values multiplied by scale
  1916. * @param scale defines the scaling factor to apply
  1917. * @returns a new Color4 object
  1918. */
  1919. Color4.prototype.scale = function (scale) {
  1920. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1921. };
  1922. /**
  1923. * Multiplies the current Color4 values by scale and stores the result in "result"
  1924. * @param scale defines the scaling factor to apply
  1925. * @param result defines the Color4 object where to store the result
  1926. * @returns the current unmodified Color4
  1927. */
  1928. Color4.prototype.scaleToRef = function (scale, result) {
  1929. result.r = this.r * scale;
  1930. result.g = this.g * scale;
  1931. result.b = this.b * scale;
  1932. result.a = this.a * scale;
  1933. return this;
  1934. };
  1935. /**
  1936. * Scale the current Color4 values by a factor and add the result to a given Color4
  1937. * @param scale defines the scale factor
  1938. * @param result defines the Color4 object where to store the result
  1939. * @returns the unmodified current Color4
  1940. */
  1941. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1942. result.r += this.r * scale;
  1943. result.g += this.g * scale;
  1944. result.b += this.b * scale;
  1945. result.a += this.a * scale;
  1946. return this;
  1947. };
  1948. /**
  1949. * Clamps the rgb values by the min and max values and stores the result into "result"
  1950. * @param min defines minimum clamping value (default is 0)
  1951. * @param max defines maximum clamping value (default is 1)
  1952. * @param result defines color to store the result into.
  1953. * @returns the cuurent Color4
  1954. */
  1955. Color4.prototype.clampToRef = function (min, max, result) {
  1956. if (min === void 0) { min = 0; }
  1957. if (max === void 0) { max = 1; }
  1958. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1959. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1960. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1961. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1962. return this;
  1963. };
  1964. /**
  1965. * Multipy an Color4 value by another and return a new Color4 object
  1966. * @param color defines the Color4 value to multiply by
  1967. * @returns a new Color4 object
  1968. */
  1969. Color4.prototype.multiply = function (color) {
  1970. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1971. };
  1972. /**
  1973. * Multipy a Color4 value by another and push the result in a reference value
  1974. * @param color defines the Color4 value to multiply by
  1975. * @param result defines the Color4 to fill the result in
  1976. * @returns the result Color4
  1977. */
  1978. Color4.prototype.multiplyToRef = function (color, result) {
  1979. result.r = this.r * color.r;
  1980. result.g = this.g * color.g;
  1981. result.b = this.b * color.b;
  1982. result.a = this.a * color.a;
  1983. return result;
  1984. };
  1985. /**
  1986. * Creates a string with the Color4 current values
  1987. * @returns the string representation of the Color4 object
  1988. */
  1989. Color4.prototype.toString = function () {
  1990. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1991. };
  1992. /**
  1993. * Returns the string "Color4"
  1994. * @returns "Color4"
  1995. */
  1996. Color4.prototype.getClassName = function () {
  1997. return "Color4";
  1998. };
  1999. /**
  2000. * Compute the Color4 hash code
  2001. * @returns an unique number that can be used to hash Color4 objects
  2002. */
  2003. Color4.prototype.getHashCode = function () {
  2004. var hash = this.r || 0;
  2005. hash = (hash * 397) ^ (this.g || 0);
  2006. hash = (hash * 397) ^ (this.b || 0);
  2007. hash = (hash * 397) ^ (this.a || 0);
  2008. return hash;
  2009. };
  2010. /**
  2011. * Creates a new Color4 copied from the current one
  2012. * @returns a new Color4 object
  2013. */
  2014. Color4.prototype.clone = function () {
  2015. return new Color4(this.r, this.g, this.b, this.a);
  2016. };
  2017. /**
  2018. * Copies the passed Color4 values into the current one
  2019. * @param source defines the source Color4 object
  2020. * @returns the current updated Color4 object
  2021. */
  2022. Color4.prototype.copyFrom = function (source) {
  2023. this.r = source.r;
  2024. this.g = source.g;
  2025. this.b = source.b;
  2026. this.a = source.a;
  2027. return this;
  2028. };
  2029. /**
  2030. * Copies the passed float values into the current one
  2031. * @param r defines the red component to read from
  2032. * @param g defines the green component to read from
  2033. * @param b defines the blue component to read from
  2034. * @param a defines the alpha component to read from
  2035. * @returns the current updated Color4 object
  2036. */
  2037. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2038. this.r = r;
  2039. this.g = g;
  2040. this.b = b;
  2041. this.a = a;
  2042. return this;
  2043. };
  2044. /**
  2045. * Copies the passed float values into the current one
  2046. * @param r defines the red component to read from
  2047. * @param g defines the green component to read from
  2048. * @param b defines the blue component to read from
  2049. * @param a defines the alpha component to read from
  2050. * @returns the current updated Color4 object
  2051. */
  2052. Color4.prototype.set = function (r, g, b, a) {
  2053. return this.copyFromFloats(r, g, b, a);
  2054. };
  2055. /**
  2056. * Compute the Color4 hexadecimal code as a string
  2057. * @returns a string containing the hexadecimal representation of the Color4 object
  2058. */
  2059. Color4.prototype.toHexString = function () {
  2060. var intR = (this.r * 255) | 0;
  2061. var intG = (this.g * 255) | 0;
  2062. var intB = (this.b * 255) | 0;
  2063. var intA = (this.a * 255) | 0;
  2064. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2065. };
  2066. /**
  2067. * Computes a new Color4 converted from the current one to linear space
  2068. * @returns a new Color4 object
  2069. */
  2070. Color4.prototype.toLinearSpace = function () {
  2071. var convertedColor = new Color4();
  2072. this.toLinearSpaceToRef(convertedColor);
  2073. return convertedColor;
  2074. };
  2075. /**
  2076. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2077. * @param convertedColor defines the Color4 object where to store the linear space version
  2078. * @returns the unmodified Color4
  2079. */
  2080. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2081. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2082. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2083. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2084. convertedColor.a = this.a;
  2085. return this;
  2086. };
  2087. /**
  2088. * Computes a new Color4 converted from the current one to gamma space
  2089. * @returns a new Color4 object
  2090. */
  2091. Color4.prototype.toGammaSpace = function () {
  2092. var convertedColor = new Color4();
  2093. this.toGammaSpaceToRef(convertedColor);
  2094. return convertedColor;
  2095. };
  2096. /**
  2097. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2098. * @param convertedColor defines the Color4 object where to store the gamma space version
  2099. * @returns the unmodified Color4
  2100. */
  2101. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2102. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2103. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2104. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2105. convertedColor.a = this.a;
  2106. return this;
  2107. };
  2108. // Statics
  2109. /**
  2110. * Creates a new Color4 from the string containing valid hexadecimal values
  2111. * @param hex defines a string containing valid hexadecimal values
  2112. * @returns a new Color4 object
  2113. */
  2114. Color4.FromHexString = function (hex) {
  2115. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2116. return new Color4(0.0, 0.0, 0.0, 0.0);
  2117. }
  2118. var r = parseInt(hex.substring(1, 3), 16);
  2119. var g = parseInt(hex.substring(3, 5), 16);
  2120. var b = parseInt(hex.substring(5, 7), 16);
  2121. var a = parseInt(hex.substring(7, 9), 16);
  2122. return Color4.FromInts(r, g, b, a);
  2123. };
  2124. /**
  2125. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2126. * @param left defines the start value
  2127. * @param right defines the end value
  2128. * @param amount defines the gradient factor
  2129. * @returns a new Color4 object
  2130. */
  2131. Color4.Lerp = function (left, right, amount) {
  2132. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2133. Color4.LerpToRef(left, right, amount, result);
  2134. return result;
  2135. };
  2136. /**
  2137. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2138. * @param left defines the start value
  2139. * @param right defines the end value
  2140. * @param amount defines the gradient factor
  2141. * @param result defines the Color4 object where to store data
  2142. */
  2143. Color4.LerpToRef = function (left, right, amount, result) {
  2144. result.r = left.r + (right.r - left.r) * amount;
  2145. result.g = left.g + (right.g - left.g) * amount;
  2146. result.b = left.b + (right.b - left.b) * amount;
  2147. result.a = left.a + (right.a - left.a) * amount;
  2148. };
  2149. /**
  2150. * Creates a new Color4 from the starting index element of the passed array
  2151. * @param array defines the source array to read from
  2152. * @param offset defines the offset in the source array
  2153. * @returns a new Color4 object
  2154. */
  2155. Color4.FromArray = function (array, offset) {
  2156. if (offset === void 0) { offset = 0; }
  2157. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2158. };
  2159. /**
  2160. * Creates a new Color3 from integer values (< 256)
  2161. * @param r defines the red component to read from (value between 0 and 255)
  2162. * @param g defines the green component to read from (value between 0 and 255)
  2163. * @param b defines the blue component to read from (value between 0 and 255)
  2164. * @param a defines the alpha component to read from (value between 0 and 255)
  2165. * @returns a new Color3 object
  2166. */
  2167. Color4.FromInts = function (r, g, b, a) {
  2168. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2169. };
  2170. /**
  2171. * Check the content of a given array and convert it to an array containing RGBA data
  2172. * If the original array was already containing count * 4 values then it is returned directly
  2173. * @param colors defines the array to check
  2174. * @param count defines the number of RGBA data to expect
  2175. * @returns an array containing count * 4 values (RGBA)
  2176. */
  2177. Color4.CheckColors4 = function (colors, count) {
  2178. // Check if color3 was used
  2179. if (colors.length === count * 3) {
  2180. var colors4 = [];
  2181. for (var index = 0; index < colors.length; index += 3) {
  2182. var newIndex = (index / 3) * 4;
  2183. colors4[newIndex] = colors[index];
  2184. colors4[newIndex + 1] = colors[index + 1];
  2185. colors4[newIndex + 2] = colors[index + 2];
  2186. colors4[newIndex + 3] = 1.0;
  2187. }
  2188. return colors4;
  2189. }
  2190. return colors;
  2191. };
  2192. return Color4;
  2193. }());
  2194. BABYLON.Color4 = Color4;
  2195. var Vector2 = /** @class */ (function () {
  2196. /**
  2197. * Creates a new Vector2 from the passed x and y coordinates.
  2198. */
  2199. function Vector2(x, y) {
  2200. this.x = x;
  2201. this.y = y;
  2202. }
  2203. /**
  2204. * Returns a string with the Vector2 coordinates.
  2205. */
  2206. Vector2.prototype.toString = function () {
  2207. return "{X: " + this.x + " Y:" + this.y + "}";
  2208. };
  2209. /**
  2210. * Returns the string "Vector2"
  2211. */
  2212. Vector2.prototype.getClassName = function () {
  2213. return "Vector2";
  2214. };
  2215. /**
  2216. * Returns the Vector2 hash code as a number.
  2217. */
  2218. Vector2.prototype.getHashCode = function () {
  2219. var hash = this.x || 0;
  2220. hash = (hash * 397) ^ (this.y || 0);
  2221. return hash;
  2222. };
  2223. // Operators
  2224. /**
  2225. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2226. * Returns the Vector2.
  2227. */
  2228. Vector2.prototype.toArray = function (array, index) {
  2229. if (index === void 0) { index = 0; }
  2230. array[index] = this.x;
  2231. array[index + 1] = this.y;
  2232. return this;
  2233. };
  2234. /**
  2235. * Returns a new array with 2 elements : the Vector2 coordinates.
  2236. */
  2237. Vector2.prototype.asArray = function () {
  2238. var result = new Array();
  2239. this.toArray(result, 0);
  2240. return result;
  2241. };
  2242. /**
  2243. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2244. * Returns the updated Vector2.
  2245. */
  2246. Vector2.prototype.copyFrom = function (source) {
  2247. this.x = source.x;
  2248. this.y = source.y;
  2249. return this;
  2250. };
  2251. /**
  2252. * Sets the Vector2 coordinates with the passed floats.
  2253. * Returns the updated Vector2.
  2254. */
  2255. Vector2.prototype.copyFromFloats = function (x, y) {
  2256. this.x = x;
  2257. this.y = y;
  2258. return this;
  2259. };
  2260. /**
  2261. * Sets the Vector2 coordinates with the passed floats.
  2262. * Returns the updated Vector2.
  2263. */
  2264. Vector2.prototype.set = function (x, y) {
  2265. return this.copyFromFloats(x, y);
  2266. };
  2267. /**
  2268. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2269. */
  2270. Vector2.prototype.add = function (otherVector) {
  2271. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2272. };
  2273. /**
  2274. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2275. * Returns the Vector2.
  2276. */
  2277. Vector2.prototype.addToRef = function (otherVector, result) {
  2278. result.x = this.x + otherVector.x;
  2279. result.y = this.y + otherVector.y;
  2280. return this;
  2281. };
  2282. /**
  2283. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2284. * Returns the updated Vector2.
  2285. */
  2286. Vector2.prototype.addInPlace = function (otherVector) {
  2287. this.x += otherVector.x;
  2288. this.y += otherVector.y;
  2289. return this;
  2290. };
  2291. /**
  2292. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2293. */
  2294. Vector2.prototype.addVector3 = function (otherVector) {
  2295. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2296. };
  2297. /**
  2298. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2299. */
  2300. Vector2.prototype.subtract = function (otherVector) {
  2301. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2302. };
  2303. /**
  2304. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2305. * Returns the Vector2.
  2306. */
  2307. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2308. result.x = this.x - otherVector.x;
  2309. result.y = this.y - otherVector.y;
  2310. return this;
  2311. };
  2312. /**
  2313. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2314. * Returns the updated Vector2.
  2315. */
  2316. Vector2.prototype.subtractInPlace = function (otherVector) {
  2317. this.x -= otherVector.x;
  2318. this.y -= otherVector.y;
  2319. return this;
  2320. };
  2321. /**
  2322. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2323. * Returns the updated Vector2.
  2324. */
  2325. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2326. this.x *= otherVector.x;
  2327. this.y *= otherVector.y;
  2328. return this;
  2329. };
  2330. /**
  2331. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2332. */
  2333. Vector2.prototype.multiply = function (otherVector) {
  2334. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2335. };
  2336. /**
  2337. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2338. * Returns the Vector2.
  2339. */
  2340. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2341. result.x = this.x * otherVector.x;
  2342. result.y = this.y * otherVector.y;
  2343. return this;
  2344. };
  2345. /**
  2346. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2347. */
  2348. Vector2.prototype.multiplyByFloats = function (x, y) {
  2349. return new Vector2(this.x * x, this.y * y);
  2350. };
  2351. /**
  2352. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2353. */
  2354. Vector2.prototype.divide = function (otherVector) {
  2355. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2356. };
  2357. /**
  2358. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2359. * Returns the Vector2.
  2360. */
  2361. Vector2.prototype.divideToRef = function (otherVector, result) {
  2362. result.x = this.x / otherVector.x;
  2363. result.y = this.y / otherVector.y;
  2364. return this;
  2365. };
  2366. /**
  2367. * Divides the current Vector3 coordinates by the passed ones.
  2368. * Returns the updated Vector3.
  2369. */
  2370. Vector2.prototype.divideInPlace = function (otherVector) {
  2371. return this.divideToRef(otherVector, this);
  2372. };
  2373. /**
  2374. * Returns a new Vector2 with current Vector2 negated coordinates.
  2375. */
  2376. Vector2.prototype.negate = function () {
  2377. return new Vector2(-this.x, -this.y);
  2378. };
  2379. /**
  2380. * Multiply the Vector2 coordinates by scale.
  2381. * Returns the updated Vector2.
  2382. */
  2383. Vector2.prototype.scaleInPlace = function (scale) {
  2384. this.x *= scale;
  2385. this.y *= scale;
  2386. return this;
  2387. };
  2388. /**
  2389. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2390. */
  2391. Vector2.prototype.scale = function (scale) {
  2392. var result = new Vector2(0, 0);
  2393. this.scaleToRef(scale, result);
  2394. return result;
  2395. };
  2396. /**
  2397. * Scale the current Vector2 values by a factor to a given Vector2
  2398. * @param scale defines the scale factor
  2399. * @param result defines the Vector2 object where to store the result
  2400. * @returns the unmodified current Vector2
  2401. */
  2402. Vector2.prototype.scaleToRef = function (scale, result) {
  2403. result.x = this.x * scale;
  2404. result.y = this.y * scale;
  2405. return this;
  2406. };
  2407. /**
  2408. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2409. * @param scale defines the scale factor
  2410. * @param result defines the Vector2 object where to store the result
  2411. * @returns the unmodified current Vector2
  2412. */
  2413. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2414. result.x += this.x * scale;
  2415. result.y += this.y * scale;
  2416. return this;
  2417. };
  2418. /**
  2419. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2420. */
  2421. Vector2.prototype.equals = function (otherVector) {
  2422. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2423. };
  2424. /**
  2425. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2426. */
  2427. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2428. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2429. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2430. };
  2431. // Properties
  2432. /**
  2433. * Returns the vector length (float).
  2434. */
  2435. Vector2.prototype.length = function () {
  2436. return Math.sqrt(this.x * this.x + this.y * this.y);
  2437. };
  2438. /**
  2439. * Returns the vector squared length (float);
  2440. */
  2441. Vector2.prototype.lengthSquared = function () {
  2442. return (this.x * this.x + this.y * this.y);
  2443. };
  2444. // Methods
  2445. /**
  2446. * Normalize the vector.
  2447. * Returns the updated Vector2.
  2448. */
  2449. Vector2.prototype.normalize = function () {
  2450. var len = this.length();
  2451. if (len === 0)
  2452. return this;
  2453. var num = 1.0 / len;
  2454. this.x *= num;
  2455. this.y *= num;
  2456. return this;
  2457. };
  2458. /**
  2459. * Returns a new Vector2 copied from the Vector2.
  2460. */
  2461. Vector2.prototype.clone = function () {
  2462. return new Vector2(this.x, this.y);
  2463. };
  2464. // Statics
  2465. /**
  2466. * Returns a new Vector2(0, 0)
  2467. */
  2468. Vector2.Zero = function () {
  2469. return new Vector2(0, 0);
  2470. };
  2471. /**
  2472. * Returns a new Vector2(1, 1)
  2473. */
  2474. Vector2.One = function () {
  2475. return new Vector2(1, 1);
  2476. };
  2477. /**
  2478. * Returns a new Vector2 set from the passed index element of the passed array.
  2479. */
  2480. Vector2.FromArray = function (array, offset) {
  2481. if (offset === void 0) { offset = 0; }
  2482. return new Vector2(array[offset], array[offset + 1]);
  2483. };
  2484. /**
  2485. * Sets "result" from the passed index element of the passed array.
  2486. */
  2487. Vector2.FromArrayToRef = function (array, offset, result) {
  2488. result.x = array[offset];
  2489. result.y = array[offset + 1];
  2490. };
  2491. /**
  2492. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2493. */
  2494. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2495. var squared = amount * amount;
  2496. var cubed = amount * squared;
  2497. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2498. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2499. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2500. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2501. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2502. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2503. return new Vector2(x, y);
  2504. };
  2505. /**
  2506. * 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".
  2507. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2508. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2509. */
  2510. Vector2.Clamp = function (value, min, max) {
  2511. var x = value.x;
  2512. x = (x > max.x) ? max.x : x;
  2513. x = (x < min.x) ? min.x : x;
  2514. var y = value.y;
  2515. y = (y > max.y) ? max.y : y;
  2516. y = (y < min.y) ? min.y : y;
  2517. return new Vector2(x, y);
  2518. };
  2519. /**
  2520. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2521. */
  2522. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2523. var squared = amount * amount;
  2524. var cubed = amount * squared;
  2525. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2526. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2527. var part3 = (cubed - (2.0 * squared)) + amount;
  2528. var part4 = cubed - squared;
  2529. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2530. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2531. return new Vector2(x, y);
  2532. };
  2533. /**
  2534. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2535. */
  2536. Vector2.Lerp = function (start, end, amount) {
  2537. var x = start.x + ((end.x - start.x) * amount);
  2538. var y = start.y + ((end.y - start.y) * amount);
  2539. return new Vector2(x, y);
  2540. };
  2541. /**
  2542. * Returns the dot product (float) of the vector "left" and the vector "right".
  2543. */
  2544. Vector2.Dot = function (left, right) {
  2545. return left.x * right.x + left.y * right.y;
  2546. };
  2547. /**
  2548. * Returns a new Vector2 equal to the normalized passed vector.
  2549. */
  2550. Vector2.Normalize = function (vector) {
  2551. var newVector = vector.clone();
  2552. newVector.normalize();
  2553. return newVector;
  2554. };
  2555. /**
  2556. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2557. */
  2558. Vector2.Minimize = function (left, right) {
  2559. var x = (left.x < right.x) ? left.x : right.x;
  2560. var y = (left.y < right.y) ? left.y : right.y;
  2561. return new Vector2(x, y);
  2562. };
  2563. /**
  2564. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2565. */
  2566. Vector2.Maximize = function (left, right) {
  2567. var x = (left.x > right.x) ? left.x : right.x;
  2568. var y = (left.y > right.y) ? left.y : right.y;
  2569. return new Vector2(x, y);
  2570. };
  2571. /**
  2572. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2573. */
  2574. Vector2.Transform = function (vector, transformation) {
  2575. var r = Vector2.Zero();
  2576. Vector2.TransformToRef(vector, transformation, r);
  2577. return r;
  2578. };
  2579. /**
  2580. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2581. */
  2582. Vector2.TransformToRef = function (vector, transformation, result) {
  2583. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2584. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2585. result.x = x;
  2586. result.y = y;
  2587. };
  2588. /**
  2589. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2590. */
  2591. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2592. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2593. var sign = a < 0 ? -1 : 1;
  2594. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2595. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2596. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2597. };
  2598. /**
  2599. * Returns the distance (float) between the vectors "value1" and "value2".
  2600. */
  2601. Vector2.Distance = function (value1, value2) {
  2602. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2603. };
  2604. /**
  2605. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2606. */
  2607. Vector2.DistanceSquared = function (value1, value2) {
  2608. var x = value1.x - value2.x;
  2609. var y = value1.y - value2.y;
  2610. return (x * x) + (y * y);
  2611. };
  2612. /**
  2613. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2614. */
  2615. Vector2.Center = function (value1, value2) {
  2616. var center = value1.add(value2);
  2617. center.scaleInPlace(0.5);
  2618. return center;
  2619. };
  2620. /**
  2621. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2622. */
  2623. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2624. var l2 = Vector2.DistanceSquared(segA, segB);
  2625. if (l2 === 0.0) {
  2626. return Vector2.Distance(p, segA);
  2627. }
  2628. var v = segB.subtract(segA);
  2629. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2630. var proj = segA.add(v.multiplyByFloats(t, t));
  2631. return Vector2.Distance(p, proj);
  2632. };
  2633. return Vector2;
  2634. }());
  2635. BABYLON.Vector2 = Vector2;
  2636. /**
  2637. * Classed used to store (x,y,z) vector representation
  2638. * A Vector3 is the main object used in 3D geometry
  2639. * It can represent etiher the coordinates of a point the space, either a direction
  2640. * Reminder: Babylon.js uses a left handed forward facing system
  2641. */
  2642. var Vector3 = /** @class */ (function () {
  2643. /**
  2644. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2645. * @param x defines the first coordinates (on X axis)
  2646. * @param y defines the second coordinates (on Y axis)
  2647. * @param z defines the third coordinates (on Z axis)
  2648. */
  2649. function Vector3(
  2650. /**
  2651. * Defines the first coordinates (on X axis)
  2652. */
  2653. x,
  2654. /**
  2655. * Defines the second coordinates (on Y axis)
  2656. */
  2657. y,
  2658. /**
  2659. * Defines the third coordinates (on Z axis)
  2660. */
  2661. z) {
  2662. this.x = x;
  2663. this.y = y;
  2664. this.z = z;
  2665. }
  2666. /**
  2667. * Creates a string representation of the Vector3
  2668. * @returns a string with the Vector3 coordinates.
  2669. */
  2670. Vector3.prototype.toString = function () {
  2671. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2672. };
  2673. /**
  2674. * Gets the class name
  2675. * @returns the string "Vector3"
  2676. */
  2677. Vector3.prototype.getClassName = function () {
  2678. return "Vector3";
  2679. };
  2680. /**
  2681. * Creates the Vector3 hash code
  2682. * @returns a number which tends to be unique between Vector3 instances
  2683. */
  2684. Vector3.prototype.getHashCode = function () {
  2685. var hash = this.x || 0;
  2686. hash = (hash * 397) ^ (this.y || 0);
  2687. hash = (hash * 397) ^ (this.z || 0);
  2688. return hash;
  2689. };
  2690. // Operators
  2691. /**
  2692. * Creates an array containing three elements : the coordinates of the Vector3
  2693. * @returns a new array of numbers
  2694. */
  2695. Vector3.prototype.asArray = function () {
  2696. var result = [];
  2697. this.toArray(result, 0);
  2698. return result;
  2699. };
  2700. /**
  2701. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2702. * @param array defines the destination array
  2703. * @param index defines the offset in the destination array
  2704. * @returns the current Vector3
  2705. */
  2706. Vector3.prototype.toArray = function (array, index) {
  2707. if (index === void 0) { index = 0; }
  2708. array[index] = this.x;
  2709. array[index + 1] = this.y;
  2710. array[index + 2] = this.z;
  2711. return this;
  2712. };
  2713. /**
  2714. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2715. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2716. */
  2717. Vector3.prototype.toQuaternion = function () {
  2718. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2719. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2720. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2721. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2722. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2723. var cosy = Math.cos(this.y * 0.5);
  2724. var siny = Math.sin(this.y * 0.5);
  2725. result.x = coszMinusx * siny;
  2726. result.y = -sinzMinusx * siny;
  2727. result.z = sinxPlusz * cosy;
  2728. result.w = cosxPlusz * cosy;
  2729. return result;
  2730. };
  2731. /**
  2732. * Adds the passed vector to the current Vector3
  2733. * @param otherVector defines the second operand
  2734. * @returns the current updated Vector3
  2735. */
  2736. Vector3.prototype.addInPlace = function (otherVector) {
  2737. this.x += otherVector.x;
  2738. this.y += otherVector.y;
  2739. this.z += otherVector.z;
  2740. return this;
  2741. };
  2742. /**
  2743. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2744. * @param otherVector defines the second operand
  2745. * @returns the resulting Vector3
  2746. */
  2747. Vector3.prototype.add = function (otherVector) {
  2748. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2749. };
  2750. /**
  2751. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2752. * @param otherVector defines the second operand
  2753. * @param result defines the Vector3 object where to store the result
  2754. * @returns the current Vector3
  2755. */
  2756. Vector3.prototype.addToRef = function (otherVector, result) {
  2757. result.x = this.x + otherVector.x;
  2758. result.y = this.y + otherVector.y;
  2759. result.z = this.z + otherVector.z;
  2760. return this;
  2761. };
  2762. /**
  2763. * Subtract the passed vector from the current Vector3
  2764. * @param otherVector defines the second operand
  2765. * @returns the current updated Vector3
  2766. */
  2767. Vector3.prototype.subtractInPlace = function (otherVector) {
  2768. this.x -= otherVector.x;
  2769. this.y -= otherVector.y;
  2770. this.z -= otherVector.z;
  2771. return this;
  2772. };
  2773. /**
  2774. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2775. * @param otherVector defines the second operand
  2776. * @returns the resulting Vector3
  2777. */
  2778. Vector3.prototype.subtract = function (otherVector) {
  2779. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2780. };
  2781. /**
  2782. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2783. * @param otherVector defines the second operand
  2784. * @param result defines the Vector3 object where to store the result
  2785. * @returns the current Vector3
  2786. */
  2787. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2788. result.x = this.x - otherVector.x;
  2789. result.y = this.y - otherVector.y;
  2790. result.z = this.z - otherVector.z;
  2791. return this;
  2792. };
  2793. /**
  2794. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2795. * @param x defines the x coordinate of the operand
  2796. * @param y defines the y coordinate of the operand
  2797. * @param z defines the z coordinate of the operand
  2798. * @returns the resulting Vector3
  2799. */
  2800. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2801. return new Vector3(this.x - x, this.y - y, this.z - z);
  2802. };
  2803. /**
  2804. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2805. * @param x defines the x coordinate of the operand
  2806. * @param y defines the y coordinate of the operand
  2807. * @param z defines the z coordinate of the operand
  2808. * @param result defines the Vector3 object where to store the result
  2809. * @returns the current Vector3
  2810. */
  2811. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2812. result.x = this.x - x;
  2813. result.y = this.y - y;
  2814. result.z = this.z - z;
  2815. return this;
  2816. };
  2817. /**
  2818. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2819. * @returns a new Vector3
  2820. */
  2821. Vector3.prototype.negate = function () {
  2822. return new Vector3(-this.x, -this.y, -this.z);
  2823. };
  2824. /**
  2825. * Multiplies the Vector3 coordinates by the float "scale"
  2826. * @param scale defines the multiplier factor
  2827. * @returns the current updated Vector3
  2828. */
  2829. Vector3.prototype.scaleInPlace = function (scale) {
  2830. this.x *= scale;
  2831. this.y *= scale;
  2832. this.z *= scale;
  2833. return this;
  2834. };
  2835. /**
  2836. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2837. * @param scale defines the multiplier factor
  2838. * @returns a new Vector3
  2839. */
  2840. Vector3.prototype.scale = function (scale) {
  2841. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2842. };
  2843. /**
  2844. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2845. * @param scale defines the multiplier factor
  2846. * @param result defines the Vector3 object where to store the result
  2847. * @returns the current Vector3
  2848. */
  2849. Vector3.prototype.scaleToRef = function (scale, result) {
  2850. result.x = this.x * scale;
  2851. result.y = this.y * scale;
  2852. result.z = this.z * scale;
  2853. return this;
  2854. };
  2855. /**
  2856. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2857. * @param scale defines the scale factor
  2858. * @param result defines the Vector3 object where to store the result
  2859. * @returns the unmodified current Vector3
  2860. */
  2861. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2862. result.x += this.x * scale;
  2863. result.y += this.y * scale;
  2864. result.z += this.z * scale;
  2865. return this;
  2866. };
  2867. /**
  2868. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2869. * @param otherVector defines the second operand
  2870. * @returns true if both vectors are equals
  2871. */
  2872. Vector3.prototype.equals = function (otherVector) {
  2873. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2874. };
  2875. /**
  2876. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2877. * @param otherVector defines the second operand
  2878. * @param epsilon defines the minimal distance to define values as equals
  2879. * @returns true if both vectors are distant less than epsilon
  2880. */
  2881. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2882. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2883. 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);
  2884. };
  2885. /**
  2886. * Returns true if the current Vector3 coordinates equals the passed floats
  2887. * @param x defines the x coordinate of the operand
  2888. * @param y defines the y coordinate of the operand
  2889. * @param z defines the z coordinate of the operand
  2890. * @returns true if both vectors are equals
  2891. */
  2892. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2893. return this.x === x && this.y === y && this.z === z;
  2894. };
  2895. /**
  2896. * Multiplies the current Vector3 coordinates by the passed ones
  2897. * @param otherVector defines the second operand
  2898. * @returns the current updated Vector3
  2899. */
  2900. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2901. this.x *= otherVector.x;
  2902. this.y *= otherVector.y;
  2903. this.z *= otherVector.z;
  2904. return this;
  2905. };
  2906. /**
  2907. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2908. * @param otherVector defines the second operand
  2909. * @returns the new Vector3
  2910. */
  2911. Vector3.prototype.multiply = function (otherVector) {
  2912. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2913. };
  2914. /**
  2915. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2916. * @param otherVector defines the second operand
  2917. * @param result defines the Vector3 object where to store the result
  2918. * @returns the current Vector3
  2919. */
  2920. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2921. result.x = this.x * otherVector.x;
  2922. result.y = this.y * otherVector.y;
  2923. result.z = this.z * otherVector.z;
  2924. return this;
  2925. };
  2926. /**
  2927. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2928. * @param x defines the x coordinate of the operand
  2929. * @param y defines the y coordinate of the operand
  2930. * @param z defines the z coordinate of the operand
  2931. * @returns the new Vector3
  2932. */
  2933. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2934. return new Vector3(this.x * x, this.y * y, this.z * z);
  2935. };
  2936. /**
  2937. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2938. * @param otherVector defines the second operand
  2939. * @returns the new Vector3
  2940. */
  2941. Vector3.prototype.divide = function (otherVector) {
  2942. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2943. };
  2944. /**
  2945. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2946. * @param otherVector defines the second operand
  2947. * @param result defines the Vector3 object where to store the result
  2948. * @returns the current Vector3
  2949. */
  2950. Vector3.prototype.divideToRef = function (otherVector, result) {
  2951. result.x = this.x / otherVector.x;
  2952. result.y = this.y / otherVector.y;
  2953. result.z = this.z / otherVector.z;
  2954. return this;
  2955. };
  2956. /**
  2957. * Divides the current Vector3 coordinates by the passed ones.
  2958. * @param otherVector defines the second operand
  2959. * @returns the current updated Vector3
  2960. */
  2961. Vector3.prototype.divideInPlace = function (otherVector) {
  2962. return this.divideToRef(otherVector, this);
  2963. };
  2964. /**
  2965. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2966. * @param other defines the second operand
  2967. * @returns the current updated Vector3
  2968. */
  2969. Vector3.prototype.minimizeInPlace = function (other) {
  2970. if (other.x < this.x)
  2971. this.x = other.x;
  2972. if (other.y < this.y)
  2973. this.y = other.y;
  2974. if (other.z < this.z)
  2975. this.z = other.z;
  2976. return this;
  2977. };
  2978. /**
  2979. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2980. * @param other defines the second operand
  2981. * @returns the current updated Vector3
  2982. */
  2983. Vector3.prototype.maximizeInPlace = function (other) {
  2984. if (other.x > this.x)
  2985. this.x = other.x;
  2986. if (other.y > this.y)
  2987. this.y = other.y;
  2988. if (other.z > this.z)
  2989. this.z = other.z;
  2990. return this;
  2991. };
  2992. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2993. /**
  2994. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2995. */
  2996. get: function () {
  2997. var absX = Math.abs(this.x);
  2998. var absY = Math.abs(this.y);
  2999. if (absX !== absY) {
  3000. return true;
  3001. }
  3002. var absZ = Math.abs(this.z);
  3003. if (absX !== absZ) {
  3004. return true;
  3005. }
  3006. if (absY !== absZ) {
  3007. return true;
  3008. }
  3009. return false;
  3010. },
  3011. enumerable: true,
  3012. configurable: true
  3013. });
  3014. // Properties
  3015. /**
  3016. * Gets the length of the Vector3
  3017. * @returns the length of the Vecto3
  3018. */
  3019. Vector3.prototype.length = function () {
  3020. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3021. };
  3022. /**
  3023. * Gets the squared length of the Vector3
  3024. * @returns squared length of the Vector3
  3025. */
  3026. Vector3.prototype.lengthSquared = function () {
  3027. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3028. };
  3029. /**
  3030. * Normalize the current Vector3.
  3031. * Please note that this is an in place operation.
  3032. * @returns the current updated Vector3
  3033. */
  3034. Vector3.prototype.normalize = function () {
  3035. var len = this.length();
  3036. if (len === 0 || len === 1.0)
  3037. return this;
  3038. var num = 1.0 / len;
  3039. this.x *= num;
  3040. this.y *= num;
  3041. this.z *= num;
  3042. return this;
  3043. };
  3044. /**
  3045. * Normalize the current Vector3 to a new vector
  3046. * @returns the new Vector3
  3047. */
  3048. Vector3.prototype.normalizeToNew = function () {
  3049. var normalized = new Vector3(0, 0, 0);
  3050. this.normalizeToRef(normalized);
  3051. return normalized;
  3052. };
  3053. /**
  3054. * Normalize the current Vector3 to the reference
  3055. * @param reference define the Vector3 to update
  3056. * @returns the updated Vector3
  3057. */
  3058. Vector3.prototype.normalizeToRef = function (reference) {
  3059. var len = this.length();
  3060. if (len === 0 || len === 1.0) {
  3061. reference.set(this.x, this.y, this.z);
  3062. return reference;
  3063. }
  3064. var scale = 1.0 / len;
  3065. this.scaleToRef(scale, reference);
  3066. return reference;
  3067. };
  3068. /**
  3069. * Creates a new Vector3 copied from the current Vector3
  3070. * @returns the new Vector3
  3071. */
  3072. Vector3.prototype.clone = function () {
  3073. return new Vector3(this.x, this.y, this.z);
  3074. };
  3075. /**
  3076. * Copies the passed vector coordinates to the current Vector3 ones
  3077. * @param source defines the source Vector3
  3078. * @returns the current updated Vector3
  3079. */
  3080. Vector3.prototype.copyFrom = function (source) {
  3081. this.x = source.x;
  3082. this.y = source.y;
  3083. this.z = source.z;
  3084. return this;
  3085. };
  3086. /**
  3087. * Copies the passed floats to the current Vector3 coordinates
  3088. * @param x defines the x coordinate of the operand
  3089. * @param y defines the y coordinate of the operand
  3090. * @param z defines the z coordinate of the operand
  3091. * @returns the current updated Vector3
  3092. */
  3093. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3094. this.x = x;
  3095. this.y = y;
  3096. this.z = z;
  3097. return this;
  3098. };
  3099. /**
  3100. * Copies the passed floats to the current Vector3 coordinates
  3101. * @param x defines the x coordinate of the operand
  3102. * @param y defines the y coordinate of the operand
  3103. * @param z defines the z coordinate of the operand
  3104. * @returns the current updated Vector3
  3105. */
  3106. Vector3.prototype.set = function (x, y, z) {
  3107. return this.copyFromFloats(x, y, z);
  3108. };
  3109. // Statics
  3110. /**
  3111. * Get the clip factor between two vectors
  3112. * @param vector0 defines the first operand
  3113. * @param vector1 defines the second operand
  3114. * @param axis defines the axis to use
  3115. * @param size defines the size along the axis
  3116. * @returns the clip factor
  3117. */
  3118. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3119. var d0 = Vector3.Dot(vector0, axis) - size;
  3120. var d1 = Vector3.Dot(vector1, axis) - size;
  3121. var s = d0 / (d0 - d1);
  3122. return s;
  3123. };
  3124. /**
  3125. * Get angle between two vectors
  3126. * @param vector0 angle between vector0 and vector1
  3127. * @param vector1 angle between vector0 and vector1
  3128. * @param normal direction of the normal
  3129. * @return the angle between vector0 and vector1
  3130. */
  3131. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3132. var v0 = vector0.clone().normalize();
  3133. var v1 = vector1.clone().normalize();
  3134. var dot = Vector3.Dot(v0, v1);
  3135. var n = Vector3.Cross(v0, v1);
  3136. if (Vector3.Dot(n, normal) > 0) {
  3137. return Math.acos(dot);
  3138. }
  3139. return -Math.acos(dot);
  3140. };
  3141. /**
  3142. * Returns a new Vector3 set from the index "offset" of the passed array
  3143. * @param array defines the source array
  3144. * @param offset defines the offset in the source array
  3145. * @returns the new Vector3
  3146. */
  3147. Vector3.FromArray = function (array, offset) {
  3148. if (!offset) {
  3149. offset = 0;
  3150. }
  3151. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3152. };
  3153. /**
  3154. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3155. * This function is deprecated. Use FromArray instead
  3156. * @param array defines the source array
  3157. * @param offset defines the offset in the source array
  3158. * @returns the new Vector3
  3159. */
  3160. Vector3.FromFloatArray = function (array, offset) {
  3161. return Vector3.FromArray(array, offset);
  3162. };
  3163. /**
  3164. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3165. * @param array defines the source array
  3166. * @param offset defines the offset in the source array
  3167. * @param result defines the Vector3 where to store the result
  3168. */
  3169. Vector3.FromArrayToRef = function (array, offset, result) {
  3170. result.x = array[offset];
  3171. result.y = array[offset + 1];
  3172. result.z = array[offset + 2];
  3173. };
  3174. /**
  3175. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3176. * This function is deprecated. Use FromArrayToRef instead.
  3177. * @param array defines the source array
  3178. * @param offset defines the offset in the source array
  3179. * @param result defines the Vector3 where to store the result
  3180. */
  3181. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3182. return Vector3.FromArrayToRef(array, offset, result);
  3183. };
  3184. /**
  3185. * Sets the passed vector "result" with the passed floats.
  3186. * @param x defines the x coordinate of the source
  3187. * @param y defines the y coordinate of the source
  3188. * @param z defines the z coordinate of the source
  3189. * @param result defines the Vector3 where to store the result
  3190. */
  3191. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3192. result.x = x;
  3193. result.y = y;
  3194. result.z = z;
  3195. };
  3196. /**
  3197. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3198. * @returns a new empty Vector3
  3199. */
  3200. Vector3.Zero = function () {
  3201. return new Vector3(0.0, 0.0, 0.0);
  3202. };
  3203. /**
  3204. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3205. * @returns a new unit Vector3
  3206. */
  3207. Vector3.One = function () {
  3208. return new Vector3(1.0, 1.0, 1.0);
  3209. };
  3210. /**
  3211. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3212. * @returns a new up Vector3
  3213. */
  3214. Vector3.Up = function () {
  3215. return new Vector3(0.0, 1.0, 0.0);
  3216. };
  3217. /**
  3218. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3219. * @returns a new forward Vector3
  3220. */
  3221. Vector3.Forward = function () {
  3222. return new Vector3(0.0, 0.0, 1.0);
  3223. };
  3224. /**
  3225. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3226. * @returns a new right Vector3
  3227. */
  3228. Vector3.Right = function () {
  3229. return new Vector3(1.0, 0.0, 0.0);
  3230. };
  3231. /**
  3232. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3233. * @returns a new left Vector3
  3234. */
  3235. Vector3.Left = function () {
  3236. return new Vector3(-1.0, 0.0, 0.0);
  3237. };
  3238. /**
  3239. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3240. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3241. * @param vector defines the Vector3 to transform
  3242. * @param transformation defines the transformation matrix
  3243. * @returns the transformed Vector3
  3244. */
  3245. Vector3.TransformCoordinates = function (vector, transformation) {
  3246. var result = Vector3.Zero();
  3247. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3248. return result;
  3249. };
  3250. /**
  3251. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3252. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3253. * @param vector defines the Vector3 to transform
  3254. * @param transformation defines the transformation matrix
  3255. * @param result defines the Vector3 where to store the result
  3256. */
  3257. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3258. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3259. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3260. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3261. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3262. result.x = x / w;
  3263. result.y = y / w;
  3264. result.z = z / w;
  3265. };
  3266. /**
  3267. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3268. * This method computes tranformed coordinates only, not transformed direction vectors
  3269. * @param x define the x coordinate of the source vector
  3270. * @param y define the y coordinate of the source vector
  3271. * @param z define the z coordinate of the source vector
  3272. * @param transformation defines the transformation matrix
  3273. * @param result defines the Vector3 where to store the result
  3274. */
  3275. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3276. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3277. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3278. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3279. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3280. result.x = rx / rw;
  3281. result.y = ry / rw;
  3282. result.z = rz / rw;
  3283. };
  3284. /**
  3285. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3286. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3287. * @param vector defines the Vector3 to transform
  3288. * @param transformation defines the transformation matrix
  3289. * @returns the new Vector3
  3290. */
  3291. Vector3.TransformNormal = function (vector, transformation) {
  3292. var result = Vector3.Zero();
  3293. Vector3.TransformNormalToRef(vector, transformation, result);
  3294. return result;
  3295. };
  3296. /**
  3297. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3298. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3299. * @param vector defines the Vector3 to transform
  3300. * @param transformation defines the transformation matrix
  3301. * @param result defines the Vector3 where to store the result
  3302. */
  3303. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3304. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3305. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3306. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3307. result.x = x;
  3308. result.y = y;
  3309. result.z = z;
  3310. };
  3311. /**
  3312. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3313. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3314. * @param x define the x coordinate of the source vector
  3315. * @param y define the y coordinate of the source vector
  3316. * @param z define the z coordinate of the source vector
  3317. * @param transformation defines the transformation matrix
  3318. * @param result defines the Vector3 where to store the result
  3319. */
  3320. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3321. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3322. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3323. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3324. };
  3325. /**
  3326. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3327. * @param value1 defines the first control point
  3328. * @param value2 defines the second control point
  3329. * @param value3 defines the third control point
  3330. * @param value4 defines the fourth control point
  3331. * @param amount defines the amount on the spline to use
  3332. * @returns the new Vector3
  3333. */
  3334. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3335. var squared = amount * amount;
  3336. var cubed = amount * squared;
  3337. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3338. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3339. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3340. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3341. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3342. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3343. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3344. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3345. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3346. return new Vector3(x, y, z);
  3347. };
  3348. /**
  3349. * 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"
  3350. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3351. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3352. * @param value defines the current value
  3353. * @param min defines the lower range value
  3354. * @param max defines the upper range value
  3355. * @returns the new Vector3
  3356. */
  3357. Vector3.Clamp = function (value, min, max) {
  3358. var x = value.x;
  3359. x = (x > max.x) ? max.x : x;
  3360. x = (x < min.x) ? min.x : x;
  3361. var y = value.y;
  3362. y = (y > max.y) ? max.y : y;
  3363. y = (y < min.y) ? min.y : y;
  3364. var z = value.z;
  3365. z = (z > max.z) ? max.z : z;
  3366. z = (z < min.z) ? min.z : z;
  3367. return new Vector3(x, y, z);
  3368. };
  3369. /**
  3370. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3371. * @param value1 defines the first control point
  3372. * @param tangent1 defines the first tangent vector
  3373. * @param value2 defines the second control point
  3374. * @param tangent2 defines the second tangent vector
  3375. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3376. * @returns the new Vector3
  3377. */
  3378. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3379. var squared = amount * amount;
  3380. var cubed = amount * squared;
  3381. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3382. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3383. var part3 = (cubed - (2.0 * squared)) + amount;
  3384. var part4 = cubed - squared;
  3385. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3386. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3387. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3388. return new Vector3(x, y, z);
  3389. };
  3390. /**
  3391. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3392. * @param start defines the start value
  3393. * @param end defines the end value
  3394. * @param amount max defines amount between both (between 0 and 1)
  3395. * @returns the new Vector3
  3396. */
  3397. Vector3.Lerp = function (start, end, amount) {
  3398. var result = new Vector3(0, 0, 0);
  3399. Vector3.LerpToRef(start, end, amount, result);
  3400. return result;
  3401. };
  3402. /**
  3403. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3404. * @param start defines the start value
  3405. * @param end defines the end value
  3406. * @param amount max defines amount between both (between 0 and 1)
  3407. * @param result defines the Vector3 where to store the result
  3408. */
  3409. Vector3.LerpToRef = function (start, end, amount, result) {
  3410. result.x = start.x + ((end.x - start.x) * amount);
  3411. result.y = start.y + ((end.y - start.y) * amount);
  3412. result.z = start.z + ((end.z - start.z) * amount);
  3413. };
  3414. /**
  3415. * Returns the dot product (float) between the vectors "left" and "right"
  3416. * @param left defines the left operand
  3417. * @param right defines the right operand
  3418. * @returns the dot product
  3419. */
  3420. Vector3.Dot = function (left, right) {
  3421. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3422. };
  3423. /**
  3424. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3425. * The cross product is then orthogonal to both "left" and "right"
  3426. * @param left defines the left operand
  3427. * @param right defines the right operand
  3428. * @returns the cross product
  3429. */
  3430. Vector3.Cross = function (left, right) {
  3431. var result = Vector3.Zero();
  3432. Vector3.CrossToRef(left, right, result);
  3433. return result;
  3434. };
  3435. /**
  3436. * Sets the passed vector "result" with the cross product of "left" and "right"
  3437. * The cross product is then orthogonal to both "left" and "right"
  3438. * @param left defines the left operand
  3439. * @param right defines the right operand
  3440. * @param result defines the Vector3 where to store the result
  3441. */
  3442. Vector3.CrossToRef = function (left, right, result) {
  3443. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3444. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3445. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3446. result.copyFrom(MathTmp.Vector3[0]);
  3447. };
  3448. /**
  3449. * Returns a new Vector3 as the normalization of the passed vector
  3450. * @param vector defines the Vector3 to normalize
  3451. * @returns the new Vector3
  3452. */
  3453. Vector3.Normalize = function (vector) {
  3454. var result = Vector3.Zero();
  3455. Vector3.NormalizeToRef(vector, result);
  3456. return result;
  3457. };
  3458. /**
  3459. * Sets the passed vector "result" with the normalization of the passed first vector
  3460. * @param vector defines the Vector3 to normalize
  3461. * @param result defines the Vector3 where to store the result
  3462. */
  3463. Vector3.NormalizeToRef = function (vector, result) {
  3464. result.copyFrom(vector);
  3465. result.normalize();
  3466. };
  3467. /**
  3468. * Project a Vector3 onto screen space
  3469. * @param vector defines the Vector3 to project
  3470. * @param world defines the world matrix to use
  3471. * @param transform defines the transform (view x projection) matrix to use
  3472. * @param viewport defines the screen viewport to use
  3473. * @returns the new Vector3
  3474. */
  3475. Vector3.Project = function (vector, world, transform, viewport) {
  3476. var cw = viewport.width;
  3477. var ch = viewport.height;
  3478. var cx = viewport.x;
  3479. var cy = viewport.y;
  3480. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3481. 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);
  3482. var matrix = MathTmp.Matrix[0];
  3483. world.multiplyToRef(transform, matrix);
  3484. matrix.multiplyToRef(viewportMatrix, matrix);
  3485. return Vector3.TransformCoordinates(vector, matrix);
  3486. };
  3487. /**
  3488. * Unproject from screen space to object space
  3489. * @param source defines the screen space Vector3 to use
  3490. * @param viewportWidth defines the current width of the viewport
  3491. * @param viewportHeight defines the current height of the viewport
  3492. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3493. * @param transform defines the transform (view x projection) matrix to use
  3494. * @returns the new Vector3
  3495. */
  3496. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3497. var matrix = MathTmp.Matrix[0];
  3498. world.multiplyToRef(transform, matrix);
  3499. matrix.invert();
  3500. source.x = source.x / viewportWidth * 2 - 1;
  3501. source.y = -(source.y / viewportHeight * 2 - 1);
  3502. var vector = Vector3.TransformCoordinates(source, matrix);
  3503. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3504. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3505. vector = vector.scale(1.0 / num);
  3506. }
  3507. return vector;
  3508. };
  3509. /**
  3510. * Unproject from screen space to object space
  3511. * @param source defines the screen space Vector3 to use
  3512. * @param viewportWidth defines the current width of the viewport
  3513. * @param viewportHeight defines the current height of the viewport
  3514. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3515. * @param view defines the view matrix to use
  3516. * @param projection defines the projection matrix to use
  3517. * @returns the new Vector3
  3518. */
  3519. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3520. var result = Vector3.Zero();
  3521. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3522. return result;
  3523. };
  3524. /**
  3525. * Unproject from screen space to object space
  3526. * @param source defines the screen space Vector3 to use
  3527. * @param viewportWidth defines the current width of the viewport
  3528. * @param viewportHeight defines the current height of the viewport
  3529. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3530. * @param view defines the view matrix to use
  3531. * @param projection defines the projection matrix to use
  3532. * @param result defines the Vector3 where to store the result
  3533. */
  3534. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3535. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3536. };
  3537. /**
  3538. * Unproject from screen space to object space
  3539. * @param sourceX defines the screen space x coordinate to use
  3540. * @param sourceY defines the screen space y coordinate to use
  3541. * @param sourceZ defines the screen space z coordinate to use
  3542. * @param viewportWidth defines the current width of the viewport
  3543. * @param viewportHeight defines the current height of the viewport
  3544. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3545. * @param view defines the view matrix to use
  3546. * @param projection defines the projection matrix to use
  3547. * @param result defines the Vector3 where to store the result
  3548. */
  3549. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3550. var matrix = MathTmp.Matrix[0];
  3551. world.multiplyToRef(view, matrix);
  3552. matrix.multiplyToRef(projection, matrix);
  3553. matrix.invert();
  3554. var screenSource = MathTmp.Vector3[0];
  3555. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3556. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3557. screenSource.z = 2 * sourceZ - 1.0;
  3558. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3559. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3560. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3561. result.scaleInPlace(1.0 / num);
  3562. }
  3563. };
  3564. /**
  3565. * Gets the minimal coordinate values between two Vector3
  3566. * @param left defines the first operand
  3567. * @param right defines the second operand
  3568. * @returns the new Vector3
  3569. */
  3570. Vector3.Minimize = function (left, right) {
  3571. var min = left.clone();
  3572. min.minimizeInPlace(right);
  3573. return min;
  3574. };
  3575. /**
  3576. * Gets the maximal coordinate values between two Vector3
  3577. * @param left defines the first operand
  3578. * @param right defines the second operand
  3579. * @returns the new Vector3
  3580. */
  3581. Vector3.Maximize = function (left, right) {
  3582. var max = left.clone();
  3583. max.maximizeInPlace(right);
  3584. return max;
  3585. };
  3586. /**
  3587. * Returns the distance between the vectors "value1" and "value2"
  3588. * @param value1 defines the first operand
  3589. * @param value2 defines the second operand
  3590. * @returns the distance
  3591. */
  3592. Vector3.Distance = function (value1, value2) {
  3593. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3594. };
  3595. /**
  3596. * Returns the squared distance between the vectors "value1" and "value2"
  3597. * @param value1 defines the first operand
  3598. * @param value2 defines the second operand
  3599. * @returns the squared distance
  3600. */
  3601. Vector3.DistanceSquared = function (value1, value2) {
  3602. var x = value1.x - value2.x;
  3603. var y = value1.y - value2.y;
  3604. var z = value1.z - value2.z;
  3605. return (x * x) + (y * y) + (z * z);
  3606. };
  3607. /**
  3608. * Returns a new Vector3 located at the center between "value1" and "value2"
  3609. * @param value1 defines the first operand
  3610. * @param value2 defines the second operand
  3611. * @returns the new Vector3
  3612. */
  3613. Vector3.Center = function (value1, value2) {
  3614. var center = value1.add(value2);
  3615. center.scaleInPlace(0.5);
  3616. return center;
  3617. };
  3618. /**
  3619. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3620. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3621. * to something in order to rotate it from its local system to the given target system
  3622. * Note: axis1, axis2 and axis3 are normalized during this operation
  3623. * @param axis1 defines the first axis
  3624. * @param axis2 defines the second axis
  3625. * @param axis3 defines the third axis
  3626. * @returns a new Vector3
  3627. */
  3628. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3629. var rotation = Vector3.Zero();
  3630. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3631. return rotation;
  3632. };
  3633. /**
  3634. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3635. * @param axis1 defines the first axis
  3636. * @param axis2 defines the second axis
  3637. * @param axis3 defines the third axis
  3638. * @param ref defines the Vector3 where to store the result
  3639. */
  3640. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3641. var quat = MathTmp.Quaternion[0];
  3642. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3643. quat.toEulerAnglesToRef(ref);
  3644. };
  3645. return Vector3;
  3646. }());
  3647. BABYLON.Vector3 = Vector3;
  3648. //Vector4 class created for EulerAngle class conversion to Quaternion
  3649. var Vector4 = /** @class */ (function () {
  3650. /**
  3651. * Creates a Vector4 object from the passed floats.
  3652. */
  3653. function Vector4(x, y, z, w) {
  3654. this.x = x;
  3655. this.y = y;
  3656. this.z = z;
  3657. this.w = w;
  3658. }
  3659. /**
  3660. * Returns the string with the Vector4 coordinates.
  3661. */
  3662. Vector4.prototype.toString = function () {
  3663. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3664. };
  3665. /**
  3666. * Returns the string "Vector4".
  3667. */
  3668. Vector4.prototype.getClassName = function () {
  3669. return "Vector4";
  3670. };
  3671. /**
  3672. * Returns the Vector4 hash code.
  3673. */
  3674. Vector4.prototype.getHashCode = function () {
  3675. var hash = this.x || 0;
  3676. hash = (hash * 397) ^ (this.y || 0);
  3677. hash = (hash * 397) ^ (this.z || 0);
  3678. hash = (hash * 397) ^ (this.w || 0);
  3679. return hash;
  3680. };
  3681. // Operators
  3682. /**
  3683. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3684. */
  3685. Vector4.prototype.asArray = function () {
  3686. var result = new Array();
  3687. this.toArray(result, 0);
  3688. return result;
  3689. };
  3690. /**
  3691. * Populates the passed array from the passed index with the Vector4 coordinates.
  3692. * Returns the Vector4.
  3693. */
  3694. Vector4.prototype.toArray = function (array, index) {
  3695. if (index === undefined) {
  3696. index = 0;
  3697. }
  3698. array[index] = this.x;
  3699. array[index + 1] = this.y;
  3700. array[index + 2] = this.z;
  3701. array[index + 3] = this.w;
  3702. return this;
  3703. };
  3704. /**
  3705. * Adds the passed vector to the current Vector4.
  3706. * Returns the updated Vector4.
  3707. */
  3708. Vector4.prototype.addInPlace = function (otherVector) {
  3709. this.x += otherVector.x;
  3710. this.y += otherVector.y;
  3711. this.z += otherVector.z;
  3712. this.w += otherVector.w;
  3713. return this;
  3714. };
  3715. /**
  3716. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3717. */
  3718. Vector4.prototype.add = function (otherVector) {
  3719. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3720. };
  3721. /**
  3722. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3723. * Returns the current Vector4.
  3724. */
  3725. Vector4.prototype.addToRef = function (otherVector, result) {
  3726. result.x = this.x + otherVector.x;
  3727. result.y = this.y + otherVector.y;
  3728. result.z = this.z + otherVector.z;
  3729. result.w = this.w + otherVector.w;
  3730. return this;
  3731. };
  3732. /**
  3733. * Subtract in place the passed vector from the current Vector4.
  3734. * Returns the updated Vector4.
  3735. */
  3736. Vector4.prototype.subtractInPlace = function (otherVector) {
  3737. this.x -= otherVector.x;
  3738. this.y -= otherVector.y;
  3739. this.z -= otherVector.z;
  3740. this.w -= otherVector.w;
  3741. return this;
  3742. };
  3743. /**
  3744. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3745. */
  3746. Vector4.prototype.subtract = function (otherVector) {
  3747. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3748. };
  3749. /**
  3750. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3751. * Returns the current Vector4.
  3752. */
  3753. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3754. result.x = this.x - otherVector.x;
  3755. result.y = this.y - otherVector.y;
  3756. result.z = this.z - otherVector.z;
  3757. result.w = this.w - otherVector.w;
  3758. return this;
  3759. };
  3760. /**
  3761. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3762. */
  3763. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3764. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3765. };
  3766. /**
  3767. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3768. * Returns the current Vector4.
  3769. */
  3770. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3771. result.x = this.x - x;
  3772. result.y = this.y - y;
  3773. result.z = this.z - z;
  3774. result.w = this.w - w;
  3775. return this;
  3776. };
  3777. /**
  3778. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3779. */
  3780. Vector4.prototype.negate = function () {
  3781. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3782. };
  3783. /**
  3784. * Multiplies the current Vector4 coordinates by scale (float).
  3785. * Returns the updated Vector4.
  3786. */
  3787. Vector4.prototype.scaleInPlace = function (scale) {
  3788. this.x *= scale;
  3789. this.y *= scale;
  3790. this.z *= scale;
  3791. this.w *= scale;
  3792. return this;
  3793. };
  3794. /**
  3795. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3796. */
  3797. Vector4.prototype.scale = function (scale) {
  3798. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3799. };
  3800. /**
  3801. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3802. * Returns the current Vector4.
  3803. */
  3804. Vector4.prototype.scaleToRef = function (scale, result) {
  3805. result.x = this.x * scale;
  3806. result.y = this.y * scale;
  3807. result.z = this.z * scale;
  3808. result.w = this.w * scale;
  3809. return this;
  3810. };
  3811. /**
  3812. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3813. * @param scale defines the scale factor
  3814. * @param result defines the Vector4 object where to store the result
  3815. * @returns the unmodified current Vector4
  3816. */
  3817. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3818. result.x += this.x * scale;
  3819. result.y += this.y * scale;
  3820. result.z += this.z * scale;
  3821. result.w += this.w * scale;
  3822. return this;
  3823. };
  3824. /**
  3825. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3826. */
  3827. Vector4.prototype.equals = function (otherVector) {
  3828. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3829. };
  3830. /**
  3831. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3832. */
  3833. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3834. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3835. return otherVector
  3836. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3837. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3838. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3839. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3840. };
  3841. /**
  3842. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3843. */
  3844. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3845. return this.x === x && this.y === y && this.z === z && this.w === w;
  3846. };
  3847. /**
  3848. * Multiplies in place the current Vector4 by the passed one.
  3849. * Returns the updated Vector4.
  3850. */
  3851. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3852. this.x *= otherVector.x;
  3853. this.y *= otherVector.y;
  3854. this.z *= otherVector.z;
  3855. this.w *= otherVector.w;
  3856. return this;
  3857. };
  3858. /**
  3859. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3860. */
  3861. Vector4.prototype.multiply = function (otherVector) {
  3862. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3863. };
  3864. /**
  3865. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3866. * Returns the current Vector4.
  3867. */
  3868. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3869. result.x = this.x * otherVector.x;
  3870. result.y = this.y * otherVector.y;
  3871. result.z = this.z * otherVector.z;
  3872. result.w = this.w * otherVector.w;
  3873. return this;
  3874. };
  3875. /**
  3876. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3877. */
  3878. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3879. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3880. };
  3881. /**
  3882. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3883. */
  3884. Vector4.prototype.divide = function (otherVector) {
  3885. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3886. };
  3887. /**
  3888. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3889. * Returns the current Vector4.
  3890. */
  3891. Vector4.prototype.divideToRef = function (otherVector, result) {
  3892. result.x = this.x / otherVector.x;
  3893. result.y = this.y / otherVector.y;
  3894. result.z = this.z / otherVector.z;
  3895. result.w = this.w / otherVector.w;
  3896. return this;
  3897. };
  3898. /**
  3899. * Divides the current Vector3 coordinates by the passed ones.
  3900. * @returns the updated Vector3.
  3901. */
  3902. Vector4.prototype.divideInPlace = function (otherVector) {
  3903. return this.divideToRef(otherVector, this);
  3904. };
  3905. /**
  3906. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3907. * @param other defines the second operand
  3908. * @returns the current updated Vector4
  3909. */
  3910. Vector4.prototype.minimizeInPlace = function (other) {
  3911. if (other.x < this.x)
  3912. this.x = other.x;
  3913. if (other.y < this.y)
  3914. this.y = other.y;
  3915. if (other.z < this.z)
  3916. this.z = other.z;
  3917. if (other.w < this.w)
  3918. this.w = other.w;
  3919. return this;
  3920. };
  3921. /**
  3922. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3923. * @param other defines the second operand
  3924. * @returns the current updated Vector4
  3925. */
  3926. Vector4.prototype.maximizeInPlace = function (other) {
  3927. if (other.x > this.x)
  3928. this.x = other.x;
  3929. if (other.y > this.y)
  3930. this.y = other.y;
  3931. if (other.z > this.z)
  3932. this.z = other.z;
  3933. if (other.w > this.w)
  3934. this.w = other.w;
  3935. return this;
  3936. };
  3937. // Properties
  3938. /**
  3939. * Returns the Vector4 length (float).
  3940. */
  3941. Vector4.prototype.length = function () {
  3942. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3943. };
  3944. /**
  3945. * Returns the Vector4 squared length (float).
  3946. */
  3947. Vector4.prototype.lengthSquared = function () {
  3948. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3949. };
  3950. // Methods
  3951. /**
  3952. * Normalizes in place the Vector4.
  3953. * Returns the updated Vector4.
  3954. */
  3955. Vector4.prototype.normalize = function () {
  3956. var len = this.length();
  3957. if (len === 0)
  3958. return this;
  3959. var num = 1.0 / len;
  3960. this.x *= num;
  3961. this.y *= num;
  3962. this.z *= num;
  3963. this.w *= num;
  3964. return this;
  3965. };
  3966. /**
  3967. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3968. */
  3969. Vector4.prototype.toVector3 = function () {
  3970. return new Vector3(this.x, this.y, this.z);
  3971. };
  3972. /**
  3973. * Returns a new Vector4 copied from the current one.
  3974. */
  3975. Vector4.prototype.clone = function () {
  3976. return new Vector4(this.x, this.y, this.z, this.w);
  3977. };
  3978. /**
  3979. * Updates the current Vector4 with the passed one coordinates.
  3980. * Returns the updated Vector4.
  3981. */
  3982. Vector4.prototype.copyFrom = function (source) {
  3983. this.x = source.x;
  3984. this.y = source.y;
  3985. this.z = source.z;
  3986. this.w = source.w;
  3987. return this;
  3988. };
  3989. /**
  3990. * Updates the current Vector4 coordinates with the passed floats.
  3991. * Returns the updated Vector4.
  3992. */
  3993. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3994. this.x = x;
  3995. this.y = y;
  3996. this.z = z;
  3997. this.w = w;
  3998. return this;
  3999. };
  4000. /**
  4001. * Updates the current Vector4 coordinates with the passed floats.
  4002. * Returns the updated Vector4.
  4003. */
  4004. Vector4.prototype.set = function (x, y, z, w) {
  4005. return this.copyFromFloats(x, y, z, w);
  4006. };
  4007. // Statics
  4008. /**
  4009. * Returns a new Vector4 set from the starting index of the passed array.
  4010. */
  4011. Vector4.FromArray = function (array, offset) {
  4012. if (!offset) {
  4013. offset = 0;
  4014. }
  4015. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4016. };
  4017. /**
  4018. * Updates the passed vector "result" from the starting index of the passed array.
  4019. */
  4020. Vector4.FromArrayToRef = function (array, offset, result) {
  4021. result.x = array[offset];
  4022. result.y = array[offset + 1];
  4023. result.z = array[offset + 2];
  4024. result.w = array[offset + 3];
  4025. };
  4026. /**
  4027. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  4028. */
  4029. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4030. Vector4.FromArrayToRef(array, offset, result);
  4031. };
  4032. /**
  4033. * Updates the passed vector "result" coordinates from the passed floats.
  4034. */
  4035. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4036. result.x = x;
  4037. result.y = y;
  4038. result.z = z;
  4039. result.w = w;
  4040. };
  4041. /**
  4042. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4043. */
  4044. Vector4.Zero = function () {
  4045. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4046. };
  4047. /**
  4048. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4049. */
  4050. Vector4.One = function () {
  4051. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4052. };
  4053. /**
  4054. * Returns a new normalized Vector4 from the passed one.
  4055. */
  4056. Vector4.Normalize = function (vector) {
  4057. var result = Vector4.Zero();
  4058. Vector4.NormalizeToRef(vector, result);
  4059. return result;
  4060. };
  4061. /**
  4062. * Updates the passed vector "result" from the normalization of the passed one.
  4063. */
  4064. Vector4.NormalizeToRef = function (vector, result) {
  4065. result.copyFrom(vector);
  4066. result.normalize();
  4067. };
  4068. Vector4.Minimize = function (left, right) {
  4069. var min = left.clone();
  4070. min.minimizeInPlace(right);
  4071. return min;
  4072. };
  4073. Vector4.Maximize = function (left, right) {
  4074. var max = left.clone();
  4075. max.maximizeInPlace(right);
  4076. return max;
  4077. };
  4078. /**
  4079. * Returns the distance (float) between the vectors "value1" and "value2".
  4080. */
  4081. Vector4.Distance = function (value1, value2) {
  4082. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4083. };
  4084. /**
  4085. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4086. */
  4087. Vector4.DistanceSquared = function (value1, value2) {
  4088. var x = value1.x - value2.x;
  4089. var y = value1.y - value2.y;
  4090. var z = value1.z - value2.z;
  4091. var w = value1.w - value2.w;
  4092. return (x * x) + (y * y) + (z * z) + (w * w);
  4093. };
  4094. /**
  4095. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4096. */
  4097. Vector4.Center = function (value1, value2) {
  4098. var center = value1.add(value2);
  4099. center.scaleInPlace(0.5);
  4100. return center;
  4101. };
  4102. /**
  4103. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4104. * This methods computes transformed normalized direction vectors only.
  4105. */
  4106. Vector4.TransformNormal = function (vector, transformation) {
  4107. var result = Vector4.Zero();
  4108. Vector4.TransformNormalToRef(vector, transformation, result);
  4109. return result;
  4110. };
  4111. /**
  4112. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4113. * This methods computes transformed normalized direction vectors only.
  4114. */
  4115. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4116. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4117. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4118. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4119. result.x = x;
  4120. result.y = y;
  4121. result.z = z;
  4122. result.w = vector.w;
  4123. };
  4124. /**
  4125. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4126. * This methods computes transformed normalized direction vectors only.
  4127. */
  4128. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4129. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4130. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4131. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4132. result.w = w;
  4133. };
  4134. return Vector4;
  4135. }());
  4136. BABYLON.Vector4 = Vector4;
  4137. var Size = /** @class */ (function () {
  4138. /**
  4139. * Creates a Size object from the passed width and height (floats).
  4140. */
  4141. function Size(width, height) {
  4142. this.width = width;
  4143. this.height = height;
  4144. }
  4145. // Returns a string with the Size width and height.
  4146. Size.prototype.toString = function () {
  4147. return "{W: " + this.width + ", H: " + this.height + "}";
  4148. };
  4149. /**
  4150. * Returns the string "Size"
  4151. */
  4152. Size.prototype.getClassName = function () {
  4153. return "Size";
  4154. };
  4155. /**
  4156. * Returns the Size hash code.
  4157. */
  4158. Size.prototype.getHashCode = function () {
  4159. var hash = this.width || 0;
  4160. hash = (hash * 397) ^ (this.height || 0);
  4161. return hash;
  4162. };
  4163. /**
  4164. * Updates the current size from the passed one.
  4165. * Returns the updated Size.
  4166. */
  4167. Size.prototype.copyFrom = function (src) {
  4168. this.width = src.width;
  4169. this.height = src.height;
  4170. };
  4171. /**
  4172. * Updates in place the current Size from the passed floats.
  4173. * Returns the updated Size.
  4174. */
  4175. Size.prototype.copyFromFloats = function (width, height) {
  4176. this.width = width;
  4177. this.height = height;
  4178. return this;
  4179. };
  4180. /**
  4181. * Updates in place the current Size from the passed floats.
  4182. * Returns the updated Size.
  4183. */
  4184. Size.prototype.set = function (width, height) {
  4185. return this.copyFromFloats(width, height);
  4186. };
  4187. /**
  4188. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4189. */
  4190. Size.prototype.multiplyByFloats = function (w, h) {
  4191. return new Size(this.width * w, this.height * h);
  4192. };
  4193. /**
  4194. * Returns a new Size copied from the passed one.
  4195. */
  4196. Size.prototype.clone = function () {
  4197. return new Size(this.width, this.height);
  4198. };
  4199. /**
  4200. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4201. */
  4202. Size.prototype.equals = function (other) {
  4203. if (!other) {
  4204. return false;
  4205. }
  4206. return (this.width === other.width) && (this.height === other.height);
  4207. };
  4208. Object.defineProperty(Size.prototype, "surface", {
  4209. /**
  4210. * Returns the surface of the Size : width * height (float).
  4211. */
  4212. get: function () {
  4213. return this.width * this.height;
  4214. },
  4215. enumerable: true,
  4216. configurable: true
  4217. });
  4218. /**
  4219. * Returns a new Size set to (0.0, 0.0)
  4220. */
  4221. Size.Zero = function () {
  4222. return new Size(0.0, 0.0);
  4223. };
  4224. /**
  4225. * Returns a new Size set as the addition result of the current Size and the passed one.
  4226. */
  4227. Size.prototype.add = function (otherSize) {
  4228. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4229. return r;
  4230. };
  4231. /**
  4232. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4233. */
  4234. Size.prototype.subtract = function (otherSize) {
  4235. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4236. return r;
  4237. };
  4238. /**
  4239. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4240. */
  4241. Size.Lerp = function (start, end, amount) {
  4242. var w = start.width + ((end.width - start.width) * amount);
  4243. var h = start.height + ((end.height - start.height) * amount);
  4244. return new Size(w, h);
  4245. };
  4246. return Size;
  4247. }());
  4248. BABYLON.Size = Size;
  4249. var Quaternion = /** @class */ (function () {
  4250. /**
  4251. * Creates a new Quaternion from the passed floats.
  4252. */
  4253. function Quaternion(x, y, z, w) {
  4254. if (x === void 0) { x = 0.0; }
  4255. if (y === void 0) { y = 0.0; }
  4256. if (z === void 0) { z = 0.0; }
  4257. if (w === void 0) { w = 1.0; }
  4258. this.x = x;
  4259. this.y = y;
  4260. this.z = z;
  4261. this.w = w;
  4262. }
  4263. /**
  4264. * Returns a string with the Quaternion coordinates.
  4265. */
  4266. Quaternion.prototype.toString = function () {
  4267. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4268. };
  4269. /**
  4270. * Returns the string "Quaternion".
  4271. */
  4272. Quaternion.prototype.getClassName = function () {
  4273. return "Quaternion";
  4274. };
  4275. /**
  4276. * Returns the Quaternion hash code.
  4277. */
  4278. Quaternion.prototype.getHashCode = function () {
  4279. var hash = this.x || 0;
  4280. hash = (hash * 397) ^ (this.y || 0);
  4281. hash = (hash * 397) ^ (this.z || 0);
  4282. hash = (hash * 397) ^ (this.w || 0);
  4283. return hash;
  4284. };
  4285. /**
  4286. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4287. */
  4288. Quaternion.prototype.asArray = function () {
  4289. return [this.x, this.y, this.z, this.w];
  4290. };
  4291. /**
  4292. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4293. */
  4294. Quaternion.prototype.equals = function (otherQuaternion) {
  4295. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4296. };
  4297. /**
  4298. * Returns a new Quaternion copied from the current one.
  4299. */
  4300. Quaternion.prototype.clone = function () {
  4301. return new Quaternion(this.x, this.y, this.z, this.w);
  4302. };
  4303. /**
  4304. * Updates the current Quaternion from the passed one coordinates.
  4305. * Returns the updated Quaterion.
  4306. */
  4307. Quaternion.prototype.copyFrom = function (other) {
  4308. this.x = other.x;
  4309. this.y = other.y;
  4310. this.z = other.z;
  4311. this.w = other.w;
  4312. return this;
  4313. };
  4314. /**
  4315. * Updates the current Quaternion from the passed float coordinates.
  4316. * Returns the updated Quaterion.
  4317. */
  4318. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4319. this.x = x;
  4320. this.y = y;
  4321. this.z = z;
  4322. this.w = w;
  4323. return this;
  4324. };
  4325. /**
  4326. * Updates the current Quaternion from the passed float coordinates.
  4327. * Returns the updated Quaterion.
  4328. */
  4329. Quaternion.prototype.set = function (x, y, z, w) {
  4330. return this.copyFromFloats(x, y, z, w);
  4331. };
  4332. /**
  4333. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4334. */
  4335. Quaternion.prototype.add = function (other) {
  4336. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4337. };
  4338. /**
  4339. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4340. */
  4341. Quaternion.prototype.subtract = function (other) {
  4342. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4343. };
  4344. /**
  4345. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4346. */
  4347. Quaternion.prototype.scale = function (value) {
  4348. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4349. };
  4350. /**
  4351. * Scale the current Quaternion values by a factor to a given Quaternion
  4352. * @param scale defines the scale factor
  4353. * @param result defines the Quaternion object where to store the result
  4354. * @returns the unmodified current Quaternion
  4355. */
  4356. Quaternion.prototype.scaleToRef = function (scale, result) {
  4357. result.x = this.x * scale;
  4358. result.y = this.y * scale;
  4359. result.z = this.z * scale;
  4360. result.w = this.w * scale;
  4361. return this;
  4362. };
  4363. /**
  4364. * Scale the current Quaternion values by a factor and add the result to a given Quaternion
  4365. * @param scale defines the scale factor
  4366. * @param result defines the Quaternion object where to store the result
  4367. * @returns the unmodified current Quaternion
  4368. */
  4369. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4370. result.x += this.x * scale;
  4371. result.y += this.y * scale;
  4372. result.z += this.z * scale;
  4373. result.w += this.w * scale;
  4374. return this;
  4375. };
  4376. /**
  4377. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4378. */
  4379. Quaternion.prototype.multiply = function (q1) {
  4380. var result = new Quaternion(0, 0, 0, 1.0);
  4381. this.multiplyToRef(q1, result);
  4382. return result;
  4383. };
  4384. /**
  4385. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4386. * Returns the current Quaternion.
  4387. */
  4388. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4389. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4390. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4391. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4392. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4393. result.copyFromFloats(x, y, z, w);
  4394. return this;
  4395. };
  4396. /**
  4397. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4398. * Returns the updated Quaternion.
  4399. */
  4400. Quaternion.prototype.multiplyInPlace = function (q1) {
  4401. this.multiplyToRef(q1, this);
  4402. return this;
  4403. };
  4404. /**
  4405. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4406. * Returns the current Quaternion.
  4407. */
  4408. Quaternion.prototype.conjugateToRef = function (ref) {
  4409. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4410. return this;
  4411. };
  4412. /**
  4413. * Conjugates in place the current Quaternion.
  4414. * Returns the updated Quaternion.
  4415. */
  4416. Quaternion.prototype.conjugateInPlace = function () {
  4417. this.x *= -1;
  4418. this.y *= -1;
  4419. this.z *= -1;
  4420. return this;
  4421. };
  4422. /**
  4423. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4424. */
  4425. Quaternion.prototype.conjugate = function () {
  4426. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4427. return result;
  4428. };
  4429. /**
  4430. * Returns the Quaternion length (float).
  4431. */
  4432. Quaternion.prototype.length = function () {
  4433. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4434. };
  4435. /**
  4436. * Normalize in place the current Quaternion.
  4437. * Returns the updated Quaternion.
  4438. */
  4439. Quaternion.prototype.normalize = function () {
  4440. var length = 1.0 / this.length();
  4441. this.x *= length;
  4442. this.y *= length;
  4443. this.z *= length;
  4444. this.w *= length;
  4445. return this;
  4446. };
  4447. /**
  4448. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion
  4449. * @param order is a reserved parameter and is ignore for now
  4450. * @returns the new Vector3
  4451. */
  4452. Quaternion.prototype.toEulerAngles = function (order) {
  4453. if (order === void 0) { order = "YZX"; }
  4454. var result = Vector3.Zero();
  4455. this.toEulerAnglesToRef(result, order);
  4456. return result;
  4457. };
  4458. /**
  4459. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion
  4460. * @param result defines the vector which will be filled with the Euler angles
  4461. * @param order is a reserved parameter and is ignore for now
  4462. * @returns the current Quaternion
  4463. */
  4464. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4465. if (order === void 0) { order = "YZX"; }
  4466. var qz = this.z;
  4467. var qx = this.x;
  4468. var qy = this.y;
  4469. var qw = this.w;
  4470. var sqw = qw * qw;
  4471. var sqz = qz * qz;
  4472. var sqx = qx * qx;
  4473. var sqy = qy * qy;
  4474. var zAxisY = qy * qz - qx * qw;
  4475. var limit = .4999999;
  4476. if (zAxisY < -limit) {
  4477. result.y = 2 * Math.atan2(qy, qw);
  4478. result.x = Math.PI / 2;
  4479. result.z = 0;
  4480. }
  4481. else if (zAxisY > limit) {
  4482. result.y = 2 * Math.atan2(qy, qw);
  4483. result.x = -Math.PI / 2;
  4484. result.z = 0;
  4485. }
  4486. else {
  4487. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4488. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4489. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4490. }
  4491. return this;
  4492. };
  4493. /**
  4494. * Updates the passed rotation matrix with the current Quaternion values.
  4495. * Returns the current Quaternion.
  4496. */
  4497. Quaternion.prototype.toRotationMatrix = function (result) {
  4498. var xx = this.x * this.x;
  4499. var yy = this.y * this.y;
  4500. var zz = this.z * this.z;
  4501. var xy = this.x * this.y;
  4502. var zw = this.z * this.w;
  4503. var zx = this.z * this.x;
  4504. var yw = this.y * this.w;
  4505. var yz = this.y * this.z;
  4506. var xw = this.x * this.w;
  4507. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4508. result.m[1] = 2.0 * (xy + zw);
  4509. result.m[2] = 2.0 * (zx - yw);
  4510. result.m[3] = 0;
  4511. result.m[4] = 2.0 * (xy - zw);
  4512. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4513. result.m[6] = 2.0 * (yz + xw);
  4514. result.m[7] = 0;
  4515. result.m[8] = 2.0 * (zx + yw);
  4516. result.m[9] = 2.0 * (yz - xw);
  4517. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4518. result.m[11] = 0;
  4519. result.m[12] = 0;
  4520. result.m[13] = 0;
  4521. result.m[14] = 0;
  4522. result.m[15] = 1.0;
  4523. result._markAsUpdated();
  4524. return this;
  4525. };
  4526. /**
  4527. * Updates the current Quaternion from the passed rotation matrix values.
  4528. * Returns the updated Quaternion.
  4529. */
  4530. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4531. Quaternion.FromRotationMatrixToRef(matrix, this);
  4532. return this;
  4533. };
  4534. // Statics
  4535. /**
  4536. * Returns a new Quaternion set from the passed rotation matrix values.
  4537. */
  4538. Quaternion.FromRotationMatrix = function (matrix) {
  4539. var result = new Quaternion();
  4540. Quaternion.FromRotationMatrixToRef(matrix, result);
  4541. return result;
  4542. };
  4543. /**
  4544. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4545. */
  4546. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4547. var data = matrix.m;
  4548. var m11 = data[0], m12 = data[4], m13 = data[8];
  4549. var m21 = data[1], m22 = data[5], m23 = data[9];
  4550. var m31 = data[2], m32 = data[6], m33 = data[10];
  4551. var trace = m11 + m22 + m33;
  4552. var s;
  4553. if (trace > 0) {
  4554. s = 0.5 / Math.sqrt(trace + 1.0);
  4555. result.w = 0.25 / s;
  4556. result.x = (m32 - m23) * s;
  4557. result.y = (m13 - m31) * s;
  4558. result.z = (m21 - m12) * s;
  4559. }
  4560. else if (m11 > m22 && m11 > m33) {
  4561. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4562. result.w = (m32 - m23) / s;
  4563. result.x = 0.25 * s;
  4564. result.y = (m12 + m21) / s;
  4565. result.z = (m13 + m31) / s;
  4566. }
  4567. else if (m22 > m33) {
  4568. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4569. result.w = (m13 - m31) / s;
  4570. result.x = (m12 + m21) / s;
  4571. result.y = 0.25 * s;
  4572. result.z = (m23 + m32) / s;
  4573. }
  4574. else {
  4575. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4576. result.w = (m21 - m12) / s;
  4577. result.x = (m13 + m31) / s;
  4578. result.y = (m23 + m32) / s;
  4579. result.z = 0.25 * s;
  4580. }
  4581. };
  4582. /**
  4583. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4584. */
  4585. Quaternion.Zero = function () {
  4586. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4587. };
  4588. /**
  4589. * Returns a new Quaternion as the inverted current Quaternion.
  4590. */
  4591. Quaternion.Inverse = function (q) {
  4592. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4593. };
  4594. /**
  4595. * Returns the identity Quaternion.
  4596. */
  4597. Quaternion.Identity = function () {
  4598. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4599. };
  4600. Quaternion.IsIdentity = function (quaternion) {
  4601. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4602. };
  4603. /**
  4604. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4605. */
  4606. Quaternion.RotationAxis = function (axis, angle) {
  4607. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4608. };
  4609. /**
  4610. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4611. */
  4612. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4613. var sin = Math.sin(angle / 2);
  4614. axis.normalize();
  4615. result.w = Math.cos(angle / 2);
  4616. result.x = axis.x * sin;
  4617. result.y = axis.y * sin;
  4618. result.z = axis.z * sin;
  4619. return result;
  4620. };
  4621. /**
  4622. * Retuns a new Quaternion set from the starting index of the passed array.
  4623. */
  4624. Quaternion.FromArray = function (array, offset) {
  4625. if (!offset) {
  4626. offset = 0;
  4627. }
  4628. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4629. };
  4630. /**
  4631. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4632. */
  4633. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4634. var q = new Quaternion();
  4635. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4636. return q;
  4637. };
  4638. /**
  4639. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4640. */
  4641. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4642. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4643. var halfRoll = roll * 0.5;
  4644. var halfPitch = pitch * 0.5;
  4645. var halfYaw = yaw * 0.5;
  4646. var sinRoll = Math.sin(halfRoll);
  4647. var cosRoll = Math.cos(halfRoll);
  4648. var sinPitch = Math.sin(halfPitch);
  4649. var cosPitch = Math.cos(halfPitch);
  4650. var sinYaw = Math.sin(halfYaw);
  4651. var cosYaw = Math.cos(halfYaw);
  4652. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4653. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4654. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4655. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4656. };
  4657. /**
  4658. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4659. */
  4660. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4661. var result = new Quaternion();
  4662. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4663. return result;
  4664. };
  4665. /**
  4666. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4667. */
  4668. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4669. // Produces a quaternion from Euler angles in the z-x-z orientation
  4670. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4671. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4672. var halfBeta = beta * 0.5;
  4673. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4674. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4675. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4676. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4677. };
  4678. /**
  4679. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4680. * cf to Vector3.RotationFromAxis() documentation.
  4681. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4682. */
  4683. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4684. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4685. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4686. return quat;
  4687. };
  4688. /**
  4689. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4690. * cf to Vector3.RotationFromAxis() documentation.
  4691. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4692. */
  4693. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4694. var rotMat = MathTmp.Matrix[0];
  4695. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4696. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4697. };
  4698. Quaternion.Slerp = function (left, right, amount) {
  4699. var result = Quaternion.Identity();
  4700. Quaternion.SlerpToRef(left, right, amount, result);
  4701. return result;
  4702. };
  4703. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4704. var num2;
  4705. var num3;
  4706. var num = amount;
  4707. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4708. var flag = false;
  4709. if (num4 < 0) {
  4710. flag = true;
  4711. num4 = -num4;
  4712. }
  4713. if (num4 > 0.999999) {
  4714. num3 = 1 - num;
  4715. num2 = flag ? -num : num;
  4716. }
  4717. else {
  4718. var num5 = Math.acos(num4);
  4719. var num6 = (1.0 / Math.sin(num5));
  4720. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4721. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4722. }
  4723. result.x = (num3 * left.x) + (num2 * right.x);
  4724. result.y = (num3 * left.y) + (num2 * right.y);
  4725. result.z = (num3 * left.z) + (num2 * right.z);
  4726. result.w = (num3 * left.w) + (num2 * right.w);
  4727. };
  4728. /**
  4729. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4730. */
  4731. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4732. var squared = amount * amount;
  4733. var cubed = amount * squared;
  4734. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4735. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4736. var part3 = (cubed - (2.0 * squared)) + amount;
  4737. var part4 = cubed - squared;
  4738. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4739. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4740. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4741. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4742. return new Quaternion(x, y, z, w);
  4743. };
  4744. return Quaternion;
  4745. }());
  4746. BABYLON.Quaternion = Quaternion;
  4747. var Matrix = /** @class */ (function () {
  4748. function Matrix() {
  4749. this._isIdentity = false;
  4750. this._isIdentityDirty = true;
  4751. this.m = new Float32Array(16);
  4752. this._markAsUpdated();
  4753. }
  4754. Matrix.prototype._markAsUpdated = function () {
  4755. this.updateFlag = Matrix._updateFlagSeed++;
  4756. this._isIdentityDirty = true;
  4757. };
  4758. // Properties
  4759. /**
  4760. * Boolean : True is the matrix is the identity matrix
  4761. */
  4762. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4763. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4764. if (this._isIdentityDirty) {
  4765. this._isIdentityDirty = false;
  4766. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4767. this._isIdentity = false;
  4768. }
  4769. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4770. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4771. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4772. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4773. this._isIdentity = false;
  4774. }
  4775. else {
  4776. this._isIdentity = true;
  4777. }
  4778. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4779. this._isIdentity = false;
  4780. }
  4781. }
  4782. return this._isIdentity;
  4783. };
  4784. /**
  4785. * Returns the matrix determinant (float).
  4786. */
  4787. Matrix.prototype.determinant = function () {
  4788. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4789. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4790. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4791. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4792. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4793. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4794. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4795. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4796. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4797. };
  4798. // Methods
  4799. /**
  4800. * Returns the matrix underlying array.
  4801. */
  4802. Matrix.prototype.toArray = function () {
  4803. return this.m;
  4804. };
  4805. /**
  4806. * Returns the matrix underlying array.
  4807. */
  4808. Matrix.prototype.asArray = function () {
  4809. return this.toArray();
  4810. };
  4811. /**
  4812. * Inverts in place the Matrix.
  4813. * Returns the Matrix inverted.
  4814. */
  4815. Matrix.prototype.invert = function () {
  4816. this.invertToRef(this);
  4817. return this;
  4818. };
  4819. /**
  4820. * Sets all the matrix elements to zero.
  4821. * Returns the Matrix.
  4822. */
  4823. Matrix.prototype.reset = function () {
  4824. for (var index = 0; index < 16; index++) {
  4825. this.m[index] = 0.0;
  4826. }
  4827. this._markAsUpdated();
  4828. return this;
  4829. };
  4830. /**
  4831. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4832. */
  4833. Matrix.prototype.add = function (other) {
  4834. var result = new Matrix();
  4835. this.addToRef(other, result);
  4836. return result;
  4837. };
  4838. /**
  4839. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4840. * Returns the Matrix.
  4841. */
  4842. Matrix.prototype.addToRef = function (other, result) {
  4843. for (var index = 0; index < 16; index++) {
  4844. result.m[index] = this.m[index] + other.m[index];
  4845. }
  4846. result._markAsUpdated();
  4847. return this;
  4848. };
  4849. /**
  4850. * Adds in place the passed matrix to the current Matrix.
  4851. * Returns the updated Matrix.
  4852. */
  4853. Matrix.prototype.addToSelf = function (other) {
  4854. for (var index = 0; index < 16; index++) {
  4855. this.m[index] += other.m[index];
  4856. }
  4857. this._markAsUpdated();
  4858. return this;
  4859. };
  4860. /**
  4861. * Sets the passed matrix with the current inverted Matrix.
  4862. * Returns the unmodified current Matrix.
  4863. */
  4864. Matrix.prototype.invertToRef = function (other) {
  4865. var l1 = this.m[0];
  4866. var l2 = this.m[1];
  4867. var l3 = this.m[2];
  4868. var l4 = this.m[3];
  4869. var l5 = this.m[4];
  4870. var l6 = this.m[5];
  4871. var l7 = this.m[6];
  4872. var l8 = this.m[7];
  4873. var l9 = this.m[8];
  4874. var l10 = this.m[9];
  4875. var l11 = this.m[10];
  4876. var l12 = this.m[11];
  4877. var l13 = this.m[12];
  4878. var l14 = this.m[13];
  4879. var l15 = this.m[14];
  4880. var l16 = this.m[15];
  4881. var l17 = (l11 * l16) - (l12 * l15);
  4882. var l18 = (l10 * l16) - (l12 * l14);
  4883. var l19 = (l10 * l15) - (l11 * l14);
  4884. var l20 = (l9 * l16) - (l12 * l13);
  4885. var l21 = (l9 * l15) - (l11 * l13);
  4886. var l22 = (l9 * l14) - (l10 * l13);
  4887. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4888. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4889. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4890. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4891. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4892. var l28 = (l7 * l16) - (l8 * l15);
  4893. var l29 = (l6 * l16) - (l8 * l14);
  4894. var l30 = (l6 * l15) - (l7 * l14);
  4895. var l31 = (l5 * l16) - (l8 * l13);
  4896. var l32 = (l5 * l15) - (l7 * l13);
  4897. var l33 = (l5 * l14) - (l6 * l13);
  4898. var l34 = (l7 * l12) - (l8 * l11);
  4899. var l35 = (l6 * l12) - (l8 * l10);
  4900. var l36 = (l6 * l11) - (l7 * l10);
  4901. var l37 = (l5 * l12) - (l8 * l9);
  4902. var l38 = (l5 * l11) - (l7 * l9);
  4903. var l39 = (l5 * l10) - (l6 * l9);
  4904. other.m[0] = l23 * l27;
  4905. other.m[4] = l24 * l27;
  4906. other.m[8] = l25 * l27;
  4907. other.m[12] = l26 * l27;
  4908. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4909. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4910. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4911. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4912. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4913. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4914. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4915. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4916. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4917. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4918. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4919. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4920. other._markAsUpdated();
  4921. return this;
  4922. };
  4923. /**
  4924. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4925. * Returns the updated Matrix.
  4926. */
  4927. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4928. this.m[12] = x;
  4929. this.m[13] = y;
  4930. this.m[14] = z;
  4931. this._markAsUpdated();
  4932. return this;
  4933. };
  4934. /**
  4935. * Inserts the translation vector in the current Matrix.
  4936. * Returns the updated Matrix.
  4937. */
  4938. Matrix.prototype.setTranslation = function (vector3) {
  4939. this.m[12] = vector3.x;
  4940. this.m[13] = vector3.y;
  4941. this.m[14] = vector3.z;
  4942. this._markAsUpdated();
  4943. return this;
  4944. };
  4945. /**
  4946. * Returns a new Vector3 as the extracted translation from the Matrix.
  4947. */
  4948. Matrix.prototype.getTranslation = function () {
  4949. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4950. };
  4951. /**
  4952. * Fill a Vector3 with the extracted translation from the Matrix.
  4953. */
  4954. Matrix.prototype.getTranslationToRef = function (result) {
  4955. result.x = this.m[12];
  4956. result.y = this.m[13];
  4957. result.z = this.m[14];
  4958. return this;
  4959. };
  4960. /**
  4961. * Remove rotation and scaling part from the Matrix.
  4962. * Returns the updated Matrix.
  4963. */
  4964. Matrix.prototype.removeRotationAndScaling = function () {
  4965. this.setRowFromFloats(0, 1, 0, 0, 0);
  4966. this.setRowFromFloats(1, 0, 1, 0, 0);
  4967. this.setRowFromFloats(2, 0, 0, 1, 0);
  4968. return this;
  4969. };
  4970. /**
  4971. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4972. */
  4973. Matrix.prototype.multiply = function (other) {
  4974. var result = new Matrix();
  4975. this.multiplyToRef(other, result);
  4976. return result;
  4977. };
  4978. /**
  4979. * Updates the current Matrix from the passed one values.
  4980. * Returns the updated Matrix.
  4981. */
  4982. Matrix.prototype.copyFrom = function (other) {
  4983. for (var index = 0; index < 16; index++) {
  4984. this.m[index] = other.m[index];
  4985. }
  4986. this._markAsUpdated();
  4987. return this;
  4988. };
  4989. /**
  4990. * Populates the passed array from the starting index with the Matrix values.
  4991. * Returns the Matrix.
  4992. */
  4993. Matrix.prototype.copyToArray = function (array, offset) {
  4994. if (offset === void 0) { offset = 0; }
  4995. for (var index = 0; index < 16; index++) {
  4996. array[offset + index] = this.m[index];
  4997. }
  4998. return this;
  4999. };
  5000. /**
  5001. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  5002. */
  5003. Matrix.prototype.multiplyToRef = function (other, result) {
  5004. this.multiplyToArray(other, result.m, 0);
  5005. result._markAsUpdated();
  5006. return this;
  5007. };
  5008. /**
  5009. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  5010. */
  5011. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5012. var tm0 = this.m[0];
  5013. var tm1 = this.m[1];
  5014. var tm2 = this.m[2];
  5015. var tm3 = this.m[3];
  5016. var tm4 = this.m[4];
  5017. var tm5 = this.m[5];
  5018. var tm6 = this.m[6];
  5019. var tm7 = this.m[7];
  5020. var tm8 = this.m[8];
  5021. var tm9 = this.m[9];
  5022. var tm10 = this.m[10];
  5023. var tm11 = this.m[11];
  5024. var tm12 = this.m[12];
  5025. var tm13 = this.m[13];
  5026. var tm14 = this.m[14];
  5027. var tm15 = this.m[15];
  5028. var om0 = other.m[0];
  5029. var om1 = other.m[1];
  5030. var om2 = other.m[2];
  5031. var om3 = other.m[3];
  5032. var om4 = other.m[4];
  5033. var om5 = other.m[5];
  5034. var om6 = other.m[6];
  5035. var om7 = other.m[7];
  5036. var om8 = other.m[8];
  5037. var om9 = other.m[9];
  5038. var om10 = other.m[10];
  5039. var om11 = other.m[11];
  5040. var om12 = other.m[12];
  5041. var om13 = other.m[13];
  5042. var om14 = other.m[14];
  5043. var om15 = other.m[15];
  5044. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5045. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5046. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5047. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5048. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5049. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5050. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5051. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5052. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5053. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5054. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5055. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5056. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5057. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5058. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5059. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5060. return this;
  5061. };
  5062. /**
  5063. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  5064. */
  5065. Matrix.prototype.equals = function (value) {
  5066. return value &&
  5067. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5068. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5069. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5070. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5071. };
  5072. /**
  5073. * Returns a new Matrix from the current Matrix.
  5074. */
  5075. Matrix.prototype.clone = function () {
  5076. 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]);
  5077. };
  5078. /**
  5079. * Returns the string "Matrix"
  5080. */
  5081. Matrix.prototype.getClassName = function () {
  5082. return "Matrix";
  5083. };
  5084. /**
  5085. * Returns the Matrix hash code.
  5086. */
  5087. Matrix.prototype.getHashCode = function () {
  5088. var hash = this.m[0] || 0;
  5089. for (var i = 1; i < 16; i++) {
  5090. hash = (hash * 397) ^ (this.m[i] || 0);
  5091. }
  5092. return hash;
  5093. };
  5094. /**
  5095. * Decomposes the current Matrix into :
  5096. * - a scale vector3 passed as a reference to update,
  5097. * - a rotation quaternion passed as a reference to update,
  5098. * - a translation vector3 passed as a reference to update.
  5099. * Returns the true if operation was successful.
  5100. */
  5101. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5102. translation.x = this.m[12];
  5103. translation.y = this.m[13];
  5104. translation.z = this.m[14];
  5105. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5106. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5107. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5108. if (this.determinant() <= 0) {
  5109. scale.y *= -1;
  5110. }
  5111. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5112. rotation.x = 0;
  5113. rotation.y = 0;
  5114. rotation.z = 0;
  5115. rotation.w = 1;
  5116. return false;
  5117. }
  5118. 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]);
  5119. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5120. return true;
  5121. };
  5122. /**
  5123. * Returns the index-th row of the current matrix as a new Vector4.
  5124. */
  5125. Matrix.prototype.getRow = function (index) {
  5126. if (index < 0 || index > 3) {
  5127. return null;
  5128. }
  5129. var i = index * 4;
  5130. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5131. };
  5132. /**
  5133. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5134. * Returns the updated Matrix.
  5135. */
  5136. Matrix.prototype.setRow = function (index, row) {
  5137. if (index < 0 || index > 3) {
  5138. return this;
  5139. }
  5140. var i = index * 4;
  5141. this.m[i + 0] = row.x;
  5142. this.m[i + 1] = row.y;
  5143. this.m[i + 2] = row.z;
  5144. this.m[i + 3] = row.w;
  5145. this._markAsUpdated();
  5146. return this;
  5147. };
  5148. /**
  5149. * Compute the transpose of the matrix.
  5150. * Returns a new Matrix.
  5151. */
  5152. Matrix.prototype.transpose = function () {
  5153. return Matrix.Transpose(this);
  5154. };
  5155. /**
  5156. * Compute the transpose of the matrix.
  5157. * Returns the current matrix.
  5158. */
  5159. Matrix.prototype.transposeToRef = function (result) {
  5160. Matrix.TransposeToRef(this, result);
  5161. return this;
  5162. };
  5163. /**
  5164. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5165. * Returns the updated Matrix.
  5166. */
  5167. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5168. if (index < 0 || index > 3) {
  5169. return this;
  5170. }
  5171. var i = index * 4;
  5172. this.m[i + 0] = x;
  5173. this.m[i + 1] = y;
  5174. this.m[i + 2] = z;
  5175. this.m[i + 3] = w;
  5176. this._markAsUpdated();
  5177. return this;
  5178. };
  5179. /**
  5180. * Compute a new Matrix set with the current Matrix values multiplied by scale (float)
  5181. * @param scale defines the scale factor
  5182. * @returns a new Matrix
  5183. */
  5184. Matrix.prototype.scale = function (scale) {
  5185. var result = new Matrix();
  5186. this.scaleToRef(scale, result);
  5187. return result;
  5188. };
  5189. /**
  5190. * Scale the current Matrix values by a factor to a given result Matrix
  5191. * @param scale defines the scale factor
  5192. * @param result defines the Matrix to store the result
  5193. * @returns the current Matrix
  5194. */
  5195. Matrix.prototype.scaleToRef = function (scale, result) {
  5196. for (var index = 0; index < 16; index++) {
  5197. result.m[index] = this.m[index] * scale;
  5198. }
  5199. result._markAsUpdated();
  5200. return this;
  5201. };
  5202. /**
  5203. * Scale the current Matrix values by a factor and add the result to a given Matrix
  5204. * @param scale defines the scale factor
  5205. * @param result defines the Matrix to store the result
  5206. * @returns the current Matrix
  5207. */
  5208. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5209. for (var index = 0; index < 16; index++) {
  5210. result.m[index] += this.m[index] * scale;
  5211. }
  5212. result._markAsUpdated();
  5213. return this;
  5214. };
  5215. /**
  5216. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5217. * @param ref matrix to store the result
  5218. */
  5219. Matrix.prototype.toNormalMatrix = function (ref) {
  5220. this.invertToRef(ref);
  5221. ref.transpose();
  5222. var m = ref.m;
  5223. 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);
  5224. };
  5225. /**
  5226. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5227. */
  5228. Matrix.prototype.getRotationMatrix = function () {
  5229. var result = Matrix.Identity();
  5230. this.getRotationMatrixToRef(result);
  5231. return result;
  5232. };
  5233. /**
  5234. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5235. * Returns the current Matrix.
  5236. */
  5237. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5238. var m = this.m;
  5239. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5240. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5241. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5242. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5243. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5244. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5245. 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);
  5246. return this;
  5247. };
  5248. // Statics
  5249. /**
  5250. * Returns a new Matrix set from the starting index of the passed array.
  5251. */
  5252. Matrix.FromArray = function (array, offset) {
  5253. var result = new Matrix();
  5254. if (!offset) {
  5255. offset = 0;
  5256. }
  5257. Matrix.FromArrayToRef(array, offset, result);
  5258. return result;
  5259. };
  5260. /**
  5261. * Sets the passed "result" matrix from the starting index of the passed array.
  5262. */
  5263. Matrix.FromArrayToRef = function (array, offset, result) {
  5264. for (var index = 0; index < 16; index++) {
  5265. result.m[index] = array[index + offset];
  5266. }
  5267. result._markAsUpdated();
  5268. };
  5269. /**
  5270. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5271. */
  5272. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5273. for (var index = 0; index < 16; index++) {
  5274. result.m[index] = array[index + offset] * scale;
  5275. }
  5276. result._markAsUpdated();
  5277. };
  5278. /**
  5279. * Sets the passed matrix "result" with the 16 passed floats.
  5280. */
  5281. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5282. result.m[0] = initialM11;
  5283. result.m[1] = initialM12;
  5284. result.m[2] = initialM13;
  5285. result.m[3] = initialM14;
  5286. result.m[4] = initialM21;
  5287. result.m[5] = initialM22;
  5288. result.m[6] = initialM23;
  5289. result.m[7] = initialM24;
  5290. result.m[8] = initialM31;
  5291. result.m[9] = initialM32;
  5292. result.m[10] = initialM33;
  5293. result.m[11] = initialM34;
  5294. result.m[12] = initialM41;
  5295. result.m[13] = initialM42;
  5296. result.m[14] = initialM43;
  5297. result.m[15] = initialM44;
  5298. result._markAsUpdated();
  5299. };
  5300. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5301. /**
  5302. * Static identity matrix to be used as readonly matrix
  5303. * Must not be updated.
  5304. */
  5305. get: function () {
  5306. return Matrix._identityReadOnly;
  5307. },
  5308. enumerable: true,
  5309. configurable: true
  5310. });
  5311. /**
  5312. * Returns a new Matrix set from the 16 passed floats.
  5313. */
  5314. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5315. var result = new Matrix();
  5316. result.m[0] = initialM11;
  5317. result.m[1] = initialM12;
  5318. result.m[2] = initialM13;
  5319. result.m[3] = initialM14;
  5320. result.m[4] = initialM21;
  5321. result.m[5] = initialM22;
  5322. result.m[6] = initialM23;
  5323. result.m[7] = initialM24;
  5324. result.m[8] = initialM31;
  5325. result.m[9] = initialM32;
  5326. result.m[10] = initialM33;
  5327. result.m[11] = initialM34;
  5328. result.m[12] = initialM41;
  5329. result.m[13] = initialM42;
  5330. result.m[14] = initialM43;
  5331. result.m[15] = initialM44;
  5332. return result;
  5333. };
  5334. /**
  5335. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5336. */
  5337. Matrix.Compose = function (scale, rotation, translation) {
  5338. var result = Matrix.Identity();
  5339. Matrix.ComposeToRef(scale, rotation, translation, result);
  5340. return result;
  5341. };
  5342. /**
  5343. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5344. */
  5345. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5346. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5347. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5348. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5349. result.setTranslation(translation);
  5350. };
  5351. /**
  5352. * Returns a new indentity Matrix.
  5353. */
  5354. Matrix.Identity = function () {
  5355. 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);
  5356. };
  5357. /**
  5358. * Sets the passed "result" as an identity matrix.
  5359. */
  5360. Matrix.IdentityToRef = function (result) {
  5361. 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);
  5362. };
  5363. /**
  5364. * Returns a new zero Matrix.
  5365. */
  5366. Matrix.Zero = function () {
  5367. 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);
  5368. };
  5369. /**
  5370. * Returns a new rotation matrix for "angle" radians around the X axis.
  5371. */
  5372. Matrix.RotationX = function (angle) {
  5373. var result = new Matrix();
  5374. Matrix.RotationXToRef(angle, result);
  5375. return result;
  5376. };
  5377. /**
  5378. * Returns a new Matrix as the passed inverted one.
  5379. */
  5380. Matrix.Invert = function (source) {
  5381. var result = new Matrix();
  5382. source.invertToRef(result);
  5383. return result;
  5384. };
  5385. /**
  5386. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5387. */
  5388. Matrix.RotationXToRef = function (angle, result) {
  5389. var s = Math.sin(angle);
  5390. var c = Math.cos(angle);
  5391. result.m[0] = 1.0;
  5392. result.m[15] = 1.0;
  5393. result.m[5] = c;
  5394. result.m[10] = c;
  5395. result.m[9] = -s;
  5396. result.m[6] = s;
  5397. result.m[1] = 0.0;
  5398. result.m[2] = 0.0;
  5399. result.m[3] = 0.0;
  5400. result.m[4] = 0.0;
  5401. result.m[7] = 0.0;
  5402. result.m[8] = 0.0;
  5403. result.m[11] = 0.0;
  5404. result.m[12] = 0.0;
  5405. result.m[13] = 0.0;
  5406. result.m[14] = 0.0;
  5407. result._markAsUpdated();
  5408. };
  5409. /**
  5410. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5411. */
  5412. Matrix.RotationY = function (angle) {
  5413. var result = new Matrix();
  5414. Matrix.RotationYToRef(angle, result);
  5415. return result;
  5416. };
  5417. /**
  5418. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5419. */
  5420. Matrix.RotationYToRef = function (angle, result) {
  5421. var s = Math.sin(angle);
  5422. var c = Math.cos(angle);
  5423. result.m[5] = 1.0;
  5424. result.m[15] = 1.0;
  5425. result.m[0] = c;
  5426. result.m[2] = -s;
  5427. result.m[8] = s;
  5428. result.m[10] = c;
  5429. result.m[1] = 0.0;
  5430. result.m[3] = 0.0;
  5431. result.m[4] = 0.0;
  5432. result.m[6] = 0.0;
  5433. result.m[7] = 0.0;
  5434. result.m[9] = 0.0;
  5435. result.m[11] = 0.0;
  5436. result.m[12] = 0.0;
  5437. result.m[13] = 0.0;
  5438. result.m[14] = 0.0;
  5439. result._markAsUpdated();
  5440. };
  5441. /**
  5442. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5443. */
  5444. Matrix.RotationZ = function (angle) {
  5445. var result = new Matrix();
  5446. Matrix.RotationZToRef(angle, result);
  5447. return result;
  5448. };
  5449. /**
  5450. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5451. */
  5452. Matrix.RotationZToRef = function (angle, result) {
  5453. var s = Math.sin(angle);
  5454. var c = Math.cos(angle);
  5455. result.m[10] = 1.0;
  5456. result.m[15] = 1.0;
  5457. result.m[0] = c;
  5458. result.m[1] = s;
  5459. result.m[4] = -s;
  5460. result.m[5] = c;
  5461. result.m[2] = 0.0;
  5462. result.m[3] = 0.0;
  5463. result.m[6] = 0.0;
  5464. result.m[7] = 0.0;
  5465. result.m[8] = 0.0;
  5466. result.m[9] = 0.0;
  5467. result.m[11] = 0.0;
  5468. result.m[12] = 0.0;
  5469. result.m[13] = 0.0;
  5470. result.m[14] = 0.0;
  5471. result._markAsUpdated();
  5472. };
  5473. /**
  5474. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5475. */
  5476. Matrix.RotationAxis = function (axis, angle) {
  5477. var result = Matrix.Zero();
  5478. Matrix.RotationAxisToRef(axis, angle, result);
  5479. return result;
  5480. };
  5481. /**
  5482. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5483. */
  5484. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5485. var s = Math.sin(-angle);
  5486. var c = Math.cos(-angle);
  5487. var c1 = 1 - c;
  5488. axis.normalize();
  5489. result.m[0] = (axis.x * axis.x) * c1 + c;
  5490. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5491. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5492. result.m[3] = 0.0;
  5493. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5494. result.m[5] = (axis.y * axis.y) * c1 + c;
  5495. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5496. result.m[7] = 0.0;
  5497. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5498. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5499. result.m[10] = (axis.z * axis.z) * c1 + c;
  5500. result.m[11] = 0.0;
  5501. result.m[15] = 1.0;
  5502. result._markAsUpdated();
  5503. };
  5504. /**
  5505. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5506. */
  5507. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5508. var result = new Matrix();
  5509. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5510. return result;
  5511. };
  5512. /**
  5513. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5514. */
  5515. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5516. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5517. this._tempQuaternion.toRotationMatrix(result);
  5518. };
  5519. /**
  5520. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5521. */
  5522. Matrix.Scaling = function (x, y, z) {
  5523. var result = Matrix.Zero();
  5524. Matrix.ScalingToRef(x, y, z, result);
  5525. return result;
  5526. };
  5527. /**
  5528. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5529. */
  5530. Matrix.ScalingToRef = function (x, y, z, result) {
  5531. result.m[0] = x;
  5532. result.m[1] = 0.0;
  5533. result.m[2] = 0.0;
  5534. result.m[3] = 0.0;
  5535. result.m[4] = 0.0;
  5536. result.m[5] = y;
  5537. result.m[6] = 0.0;
  5538. result.m[7] = 0.0;
  5539. result.m[8] = 0.0;
  5540. result.m[9] = 0.0;
  5541. result.m[10] = z;
  5542. result.m[11] = 0.0;
  5543. result.m[12] = 0.0;
  5544. result.m[13] = 0.0;
  5545. result.m[14] = 0.0;
  5546. result.m[15] = 1.0;
  5547. result._markAsUpdated();
  5548. };
  5549. /**
  5550. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5551. */
  5552. Matrix.Translation = function (x, y, z) {
  5553. var result = Matrix.Identity();
  5554. Matrix.TranslationToRef(x, y, z, result);
  5555. return result;
  5556. };
  5557. /**
  5558. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5559. */
  5560. Matrix.TranslationToRef = function (x, y, z, result) {
  5561. 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);
  5562. };
  5563. /**
  5564. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5565. * @param startValue defines the start value
  5566. * @param endValue defines the end value
  5567. * @param gradient defines the gradient factor
  5568. * @returns the new matrix
  5569. */
  5570. Matrix.Lerp = function (startValue, endValue, gradient) {
  5571. var result = Matrix.Zero();
  5572. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5573. return result;
  5574. };
  5575. /**
  5576. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5577. * @param startValue defines the start value
  5578. * @param endValue defines the end value
  5579. * @param gradient defines the gradient factor
  5580. * @param result defines the Matrix object where to store data
  5581. */
  5582. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5583. for (var index = 0; index < 16; index++) {
  5584. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5585. }
  5586. result._markAsUpdated();
  5587. };
  5588. /**
  5589. * Returns a new Matrix whose values are computed by :
  5590. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5591. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5592. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5593. */
  5594. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5595. var startScale = new Vector3(0, 0, 0);
  5596. var startRotation = new Quaternion();
  5597. var startTranslation = new Vector3(0, 0, 0);
  5598. startValue.decompose(startScale, startRotation, startTranslation);
  5599. var endScale = new Vector3(0, 0, 0);
  5600. var endRotation = new Quaternion();
  5601. var endTranslation = new Vector3(0, 0, 0);
  5602. endValue.decompose(endScale, endRotation, endTranslation);
  5603. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5604. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5605. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5606. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5607. };
  5608. /**
  5609. * 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".
  5610. * This methods works for a Left-Handed system.
  5611. */
  5612. Matrix.LookAtLH = function (eye, target, up) {
  5613. var result = Matrix.Zero();
  5614. Matrix.LookAtLHToRef(eye, target, up, result);
  5615. return result;
  5616. };
  5617. /**
  5618. * 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".
  5619. * This methods works for a Left-Handed system.
  5620. */
  5621. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5622. // Z axis
  5623. target.subtractToRef(eye, this._zAxis);
  5624. this._zAxis.normalize();
  5625. // X axis
  5626. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5627. if (this._xAxis.lengthSquared() === 0) {
  5628. this._xAxis.x = 1.0;
  5629. }
  5630. else {
  5631. this._xAxis.normalize();
  5632. }
  5633. // Y axis
  5634. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5635. this._yAxis.normalize();
  5636. // Eye angles
  5637. var ex = -Vector3.Dot(this._xAxis, eye);
  5638. var ey = -Vector3.Dot(this._yAxis, eye);
  5639. var ez = -Vector3.Dot(this._zAxis, eye);
  5640. 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);
  5641. };
  5642. /**
  5643. * 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".
  5644. * This methods works for a Right-Handed system.
  5645. */
  5646. Matrix.LookAtRH = function (eye, target, up) {
  5647. var result = Matrix.Zero();
  5648. Matrix.LookAtRHToRef(eye, target, up, result);
  5649. return result;
  5650. };
  5651. /**
  5652. * 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".
  5653. * This methods works for a Left-Handed system.
  5654. */
  5655. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5656. // Z axis
  5657. eye.subtractToRef(target, this._zAxis);
  5658. this._zAxis.normalize();
  5659. // X axis
  5660. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5661. if (this._xAxis.lengthSquared() === 0) {
  5662. this._xAxis.x = 1.0;
  5663. }
  5664. else {
  5665. this._xAxis.normalize();
  5666. }
  5667. // Y axis
  5668. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5669. this._yAxis.normalize();
  5670. // Eye angles
  5671. var ex = -Vector3.Dot(this._xAxis, eye);
  5672. var ey = -Vector3.Dot(this._yAxis, eye);
  5673. var ez = -Vector3.Dot(this._zAxis, eye);
  5674. 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);
  5675. };
  5676. /**
  5677. * 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.
  5678. */
  5679. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5680. var matrix = Matrix.Zero();
  5681. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5682. return matrix;
  5683. };
  5684. /**
  5685. * 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.
  5686. */
  5687. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5688. var n = znear;
  5689. var f = zfar;
  5690. var a = 2.0 / width;
  5691. var b = 2.0 / height;
  5692. var c = 2.0 / (f - n);
  5693. var d = -(f + n) / (f - n);
  5694. 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);
  5695. };
  5696. /**
  5697. * 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.
  5698. */
  5699. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5700. var matrix = Matrix.Zero();
  5701. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5702. return matrix;
  5703. };
  5704. /**
  5705. * 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.
  5706. */
  5707. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5708. var n = znear;
  5709. var f = zfar;
  5710. var a = 2.0 / (right - left);
  5711. var b = 2.0 / (top - bottom);
  5712. var c = 2.0 / (f - n);
  5713. var d = -(f + n) / (f - n);
  5714. var i0 = (left + right) / (left - right);
  5715. var i1 = (top + bottom) / (bottom - top);
  5716. 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);
  5717. };
  5718. /**
  5719. * 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.
  5720. */
  5721. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5722. var matrix = Matrix.Zero();
  5723. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5724. return matrix;
  5725. };
  5726. /**
  5727. * 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.
  5728. */
  5729. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5730. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5731. result.m[10] *= -1.0;
  5732. };
  5733. /**
  5734. * 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.
  5735. */
  5736. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5737. var matrix = Matrix.Zero();
  5738. var n = znear;
  5739. var f = zfar;
  5740. var a = 2.0 * n / width;
  5741. var b = 2.0 * n / height;
  5742. var c = (f + n) / (f - n);
  5743. var d = -2.0 * f * n / (f - n);
  5744. 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);
  5745. return matrix;
  5746. };
  5747. /**
  5748. * 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.
  5749. */
  5750. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5751. var matrix = Matrix.Zero();
  5752. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5753. return matrix;
  5754. };
  5755. /**
  5756. * 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.
  5757. */
  5758. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5759. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5760. var n = znear;
  5761. var f = zfar;
  5762. var t = 1.0 / (Math.tan(fov * 0.5));
  5763. var a = isVerticalFovFixed ? (t / aspect) : t;
  5764. var b = isVerticalFovFixed ? t : (t * aspect);
  5765. var c = (f + n) / (f - n);
  5766. var d = -2.0 * f * n / (f - n);
  5767. 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);
  5768. };
  5769. /**
  5770. * 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.
  5771. */
  5772. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5773. var matrix = Matrix.Zero();
  5774. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5775. return matrix;
  5776. };
  5777. /**
  5778. * 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.
  5779. */
  5780. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5781. //alternatively this could be expressed as:
  5782. // m = PerspectiveFovLHToRef
  5783. // m[10] *= -1.0;
  5784. // m[11] *= -1.0;
  5785. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5786. var n = znear;
  5787. var f = zfar;
  5788. var t = 1.0 / (Math.tan(fov * 0.5));
  5789. var a = isVerticalFovFixed ? (t / aspect) : t;
  5790. var b = isVerticalFovFixed ? t : (t * aspect);
  5791. var c = -(f + n) / (f - n);
  5792. var d = -2 * f * n / (f - n);
  5793. 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);
  5794. };
  5795. /**
  5796. * 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.
  5797. */
  5798. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5799. if (rightHanded === void 0) { rightHanded = false; }
  5800. var rightHandedFactor = rightHanded ? -1 : 1;
  5801. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5802. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5803. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5804. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5805. var xScale = 2.0 / (leftTan + rightTan);
  5806. var yScale = 2.0 / (upTan + downTan);
  5807. result.m[0] = xScale;
  5808. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5809. result.m[5] = yScale;
  5810. result.m[6] = result.m[7] = 0.0;
  5811. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5812. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5813. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5814. result.m[10] = -zfar / (znear - zfar);
  5815. result.m[11] = 1.0 * rightHandedFactor;
  5816. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5817. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5818. // result.m[14] = (znear * zfar) / (znear - zfar);
  5819. result._markAsUpdated();
  5820. };
  5821. /**
  5822. * Returns the final transformation matrix : world * view * projection * viewport
  5823. */
  5824. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5825. var cw = viewport.width;
  5826. var ch = viewport.height;
  5827. var cx = viewport.x;
  5828. var cy = viewport.y;
  5829. 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);
  5830. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5831. };
  5832. /**
  5833. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5834. */
  5835. Matrix.GetAsMatrix2x2 = function (matrix) {
  5836. return new Float32Array([
  5837. matrix.m[0], matrix.m[1],
  5838. matrix.m[4], matrix.m[5]
  5839. ]);
  5840. };
  5841. /**
  5842. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5843. */
  5844. Matrix.GetAsMatrix3x3 = function (matrix) {
  5845. return new Float32Array([
  5846. matrix.m[0], matrix.m[1], matrix.m[2],
  5847. matrix.m[4], matrix.m[5], matrix.m[6],
  5848. matrix.m[8], matrix.m[9], matrix.m[10]
  5849. ]);
  5850. };
  5851. /**
  5852. * Compute the transpose of the passed Matrix.
  5853. * Returns a new Matrix.
  5854. */
  5855. Matrix.Transpose = function (matrix) {
  5856. var result = new Matrix();
  5857. Matrix.TransposeToRef(matrix, result);
  5858. return result;
  5859. };
  5860. /**
  5861. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5862. */
  5863. Matrix.TransposeToRef = function (matrix, result) {
  5864. result.m[0] = matrix.m[0];
  5865. result.m[1] = matrix.m[4];
  5866. result.m[2] = matrix.m[8];
  5867. result.m[3] = matrix.m[12];
  5868. result.m[4] = matrix.m[1];
  5869. result.m[5] = matrix.m[5];
  5870. result.m[6] = matrix.m[9];
  5871. result.m[7] = matrix.m[13];
  5872. result.m[8] = matrix.m[2];
  5873. result.m[9] = matrix.m[6];
  5874. result.m[10] = matrix.m[10];
  5875. result.m[11] = matrix.m[14];
  5876. result.m[12] = matrix.m[3];
  5877. result.m[13] = matrix.m[7];
  5878. result.m[14] = matrix.m[11];
  5879. result.m[15] = matrix.m[15];
  5880. };
  5881. /**
  5882. * Returns a new Matrix as the reflection matrix across the passed plane.
  5883. */
  5884. Matrix.Reflection = function (plane) {
  5885. var matrix = new Matrix();
  5886. Matrix.ReflectionToRef(plane, matrix);
  5887. return matrix;
  5888. };
  5889. /**
  5890. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5891. */
  5892. Matrix.ReflectionToRef = function (plane, result) {
  5893. plane.normalize();
  5894. var x = plane.normal.x;
  5895. var y = plane.normal.y;
  5896. var z = plane.normal.z;
  5897. var temp = -2 * x;
  5898. var temp2 = -2 * y;
  5899. var temp3 = -2 * z;
  5900. result.m[0] = (temp * x) + 1;
  5901. result.m[1] = temp2 * x;
  5902. result.m[2] = temp3 * x;
  5903. result.m[3] = 0.0;
  5904. result.m[4] = temp * y;
  5905. result.m[5] = (temp2 * y) + 1;
  5906. result.m[6] = temp3 * y;
  5907. result.m[7] = 0.0;
  5908. result.m[8] = temp * z;
  5909. result.m[9] = temp2 * z;
  5910. result.m[10] = (temp3 * z) + 1;
  5911. result.m[11] = 0.0;
  5912. result.m[12] = temp * plane.d;
  5913. result.m[13] = temp2 * plane.d;
  5914. result.m[14] = temp3 * plane.d;
  5915. result.m[15] = 1.0;
  5916. result._markAsUpdated();
  5917. };
  5918. /**
  5919. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5920. */
  5921. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5922. result.m[0] = xaxis.x;
  5923. result.m[1] = xaxis.y;
  5924. result.m[2] = xaxis.z;
  5925. result.m[3] = 0.0;
  5926. result.m[4] = yaxis.x;
  5927. result.m[5] = yaxis.y;
  5928. result.m[6] = yaxis.z;
  5929. result.m[7] = 0.0;
  5930. result.m[8] = zaxis.x;
  5931. result.m[9] = zaxis.y;
  5932. result.m[10] = zaxis.z;
  5933. result.m[11] = 0.0;
  5934. result.m[12] = 0.0;
  5935. result.m[13] = 0.0;
  5936. result.m[14] = 0.0;
  5937. result.m[15] = 1.0;
  5938. result._markAsUpdated();
  5939. };
  5940. /**
  5941. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5942. */
  5943. Matrix.FromQuaternionToRef = function (quat, result) {
  5944. var xx = quat.x * quat.x;
  5945. var yy = quat.y * quat.y;
  5946. var zz = quat.z * quat.z;
  5947. var xy = quat.x * quat.y;
  5948. var zw = quat.z * quat.w;
  5949. var zx = quat.z * quat.x;
  5950. var yw = quat.y * quat.w;
  5951. var yz = quat.y * quat.z;
  5952. var xw = quat.x * quat.w;
  5953. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5954. result.m[1] = 2.0 * (xy + zw);
  5955. result.m[2] = 2.0 * (zx - yw);
  5956. result.m[3] = 0.0;
  5957. result.m[4] = 2.0 * (xy - zw);
  5958. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5959. result.m[6] = 2.0 * (yz + xw);
  5960. result.m[7] = 0.0;
  5961. result.m[8] = 2.0 * (zx + yw);
  5962. result.m[9] = 2.0 * (yz - xw);
  5963. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5964. result.m[11] = 0.0;
  5965. result.m[12] = 0.0;
  5966. result.m[13] = 0.0;
  5967. result.m[14] = 0.0;
  5968. result.m[15] = 1.0;
  5969. result._markAsUpdated();
  5970. };
  5971. Matrix._tempQuaternion = new Quaternion();
  5972. Matrix._xAxis = Vector3.Zero();
  5973. Matrix._yAxis = Vector3.Zero();
  5974. Matrix._zAxis = Vector3.Zero();
  5975. Matrix._updateFlagSeed = 0;
  5976. Matrix._identityReadOnly = Matrix.Identity();
  5977. return Matrix;
  5978. }());
  5979. BABYLON.Matrix = Matrix;
  5980. var Plane = /** @class */ (function () {
  5981. /**
  5982. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5983. */
  5984. function Plane(a, b, c, d) {
  5985. this.normal = new Vector3(a, b, c);
  5986. this.d = d;
  5987. }
  5988. /**
  5989. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5990. */
  5991. Plane.prototype.asArray = function () {
  5992. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5993. };
  5994. // Methods
  5995. /**
  5996. * Returns a new plane copied from the current Plane.
  5997. */
  5998. Plane.prototype.clone = function () {
  5999. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6000. };
  6001. /**
  6002. * Returns the string "Plane".
  6003. */
  6004. Plane.prototype.getClassName = function () {
  6005. return "Plane";
  6006. };
  6007. /**
  6008. * Returns the Plane hash code.
  6009. */
  6010. Plane.prototype.getHashCode = function () {
  6011. var hash = this.normal.getHashCode();
  6012. hash = (hash * 397) ^ (this.d || 0);
  6013. return hash;
  6014. };
  6015. /**
  6016. * Normalize the current Plane in place.
  6017. * Returns the updated Plane.
  6018. */
  6019. Plane.prototype.normalize = function () {
  6020. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6021. var magnitude = 0.0;
  6022. if (norm !== 0) {
  6023. magnitude = 1.0 / norm;
  6024. }
  6025. this.normal.x *= magnitude;
  6026. this.normal.y *= magnitude;
  6027. this.normal.z *= magnitude;
  6028. this.d *= magnitude;
  6029. return this;
  6030. };
  6031. /**
  6032. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  6033. */
  6034. Plane.prototype.transform = function (transformation) {
  6035. var transposedMatrix = Matrix.Transpose(transformation);
  6036. var x = this.normal.x;
  6037. var y = this.normal.y;
  6038. var z = this.normal.z;
  6039. var d = this.d;
  6040. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6041. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6042. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6043. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6044. return new Plane(normalX, normalY, normalZ, finalD);
  6045. };
  6046. /**
  6047. * Returns the dot product (float) of the point coordinates and the plane normal.
  6048. */
  6049. Plane.prototype.dotCoordinate = function (point) {
  6050. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6051. };
  6052. /**
  6053. * Updates the current Plane from the plane defined by the three passed points.
  6054. * Returns the updated Plane.
  6055. */
  6056. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6057. var x1 = point2.x - point1.x;
  6058. var y1 = point2.y - point1.y;
  6059. var z1 = point2.z - point1.z;
  6060. var x2 = point3.x - point1.x;
  6061. var y2 = point3.y - point1.y;
  6062. var z2 = point3.z - point1.z;
  6063. var yz = (y1 * z2) - (z1 * y2);
  6064. var xz = (z1 * x2) - (x1 * z2);
  6065. var xy = (x1 * y2) - (y1 * x2);
  6066. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6067. var invPyth;
  6068. if (pyth !== 0) {
  6069. invPyth = 1.0 / pyth;
  6070. }
  6071. else {
  6072. invPyth = 0.0;
  6073. }
  6074. this.normal.x = yz * invPyth;
  6075. this.normal.y = xz * invPyth;
  6076. this.normal.z = xy * invPyth;
  6077. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6078. return this;
  6079. };
  6080. /**
  6081. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6082. */
  6083. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6084. var dot = Vector3.Dot(this.normal, direction);
  6085. return (dot <= epsilon);
  6086. };
  6087. /**
  6088. * Returns the signed distance (float) from the passed point to the Plane.
  6089. */
  6090. Plane.prototype.signedDistanceTo = function (point) {
  6091. return Vector3.Dot(point, this.normal) + this.d;
  6092. };
  6093. // Statics
  6094. /**
  6095. * Returns a new Plane from the passed array.
  6096. */
  6097. Plane.FromArray = function (array) {
  6098. return new Plane(array[0], array[1], array[2], array[3]);
  6099. };
  6100. /**
  6101. * Returns a new Plane defined by the three passed points.
  6102. */
  6103. Plane.FromPoints = function (point1, point2, point3) {
  6104. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6105. result.copyFromPoints(point1, point2, point3);
  6106. return result;
  6107. };
  6108. /**
  6109. * Returns a new Plane the normal vector to this plane at the passed origin point.
  6110. * Note : the vector "normal" is updated because normalized.
  6111. */
  6112. Plane.FromPositionAndNormal = function (origin, normal) {
  6113. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6114. normal.normalize();
  6115. result.normal = normal;
  6116. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6117. return result;
  6118. };
  6119. /**
  6120. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  6121. */
  6122. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6123. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6124. return Vector3.Dot(point, normal) + d;
  6125. };
  6126. return Plane;
  6127. }());
  6128. BABYLON.Plane = Plane;
  6129. var Viewport = /** @class */ (function () {
  6130. /**
  6131. * Creates a Viewport object located at (x, y) and sized (width, height).
  6132. */
  6133. function Viewport(x, y, width, height) {
  6134. this.x = x;
  6135. this.y = y;
  6136. this.width = width;
  6137. this.height = height;
  6138. }
  6139. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6140. if (renderWidthOrEngine.getRenderWidth) {
  6141. var engine = renderWidthOrEngine;
  6142. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6143. }
  6144. var renderWidth = renderWidthOrEngine;
  6145. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6146. };
  6147. /**
  6148. * Returns a new Viewport copied from the current one.
  6149. */
  6150. Viewport.prototype.clone = function () {
  6151. return new Viewport(this.x, this.y, this.width, this.height);
  6152. };
  6153. return Viewport;
  6154. }());
  6155. BABYLON.Viewport = Viewport;
  6156. var Frustum = /** @class */ (function () {
  6157. function Frustum() {
  6158. }
  6159. /**
  6160. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6161. */
  6162. Frustum.GetPlanes = function (transform) {
  6163. var frustumPlanes = [];
  6164. for (var index = 0; index < 6; index++) {
  6165. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6166. }
  6167. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6168. return frustumPlanes;
  6169. };
  6170. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6171. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6172. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6173. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6174. frustumPlane.d = transform.m[15] + transform.m[14];
  6175. frustumPlane.normalize();
  6176. };
  6177. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6178. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6179. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6180. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6181. frustumPlane.d = transform.m[15] - transform.m[14];
  6182. frustumPlane.normalize();
  6183. };
  6184. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6185. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6186. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6187. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6188. frustumPlane.d = transform.m[15] + transform.m[12];
  6189. frustumPlane.normalize();
  6190. };
  6191. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6192. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6193. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6194. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6195. frustumPlane.d = transform.m[15] - transform.m[12];
  6196. frustumPlane.normalize();
  6197. };
  6198. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6199. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6200. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6201. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6202. frustumPlane.d = transform.m[15] - transform.m[13];
  6203. frustumPlane.normalize();
  6204. };
  6205. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6206. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6207. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6208. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6209. frustumPlane.d = transform.m[15] + transform.m[13];
  6210. frustumPlane.normalize();
  6211. };
  6212. /**
  6213. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6214. */
  6215. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6216. // Near
  6217. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6218. // Far
  6219. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6220. // Left
  6221. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6222. // Right
  6223. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6224. // Top
  6225. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6226. // Bottom
  6227. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6228. };
  6229. return Frustum;
  6230. }());
  6231. BABYLON.Frustum = Frustum;
  6232. var Space;
  6233. (function (Space) {
  6234. Space[Space["LOCAL"] = 0] = "LOCAL";
  6235. Space[Space["WORLD"] = 1] = "WORLD";
  6236. Space[Space["BONE"] = 2] = "BONE";
  6237. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6238. var Axis = /** @class */ (function () {
  6239. function Axis() {
  6240. }
  6241. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6242. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6243. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6244. return Axis;
  6245. }());
  6246. BABYLON.Axis = Axis;
  6247. ;
  6248. var BezierCurve = /** @class */ (function () {
  6249. function BezierCurve() {
  6250. }
  6251. /**
  6252. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6253. */
  6254. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6255. // Extract X (which is equal to time here)
  6256. var f0 = 1 - 3 * x2 + 3 * x1;
  6257. var f1 = 3 * x2 - 6 * x1;
  6258. var f2 = 3 * x1;
  6259. var refinedT = t;
  6260. for (var i = 0; i < 5; i++) {
  6261. var refinedT2 = refinedT * refinedT;
  6262. var refinedT3 = refinedT2 * refinedT;
  6263. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6264. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6265. refinedT -= (x - t) * slope;
  6266. refinedT = Math.min(1, Math.max(0, refinedT));
  6267. }
  6268. // Resolve cubic bezier for the given x
  6269. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6270. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6271. Math.pow(refinedT, 3);
  6272. };
  6273. return BezierCurve;
  6274. }());
  6275. BABYLON.BezierCurve = BezierCurve;
  6276. var Orientation;
  6277. (function (Orientation) {
  6278. Orientation[Orientation["CW"] = 0] = "CW";
  6279. Orientation[Orientation["CCW"] = 1] = "CCW";
  6280. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6281. var Angle = /** @class */ (function () {
  6282. /**
  6283. * Creates an Angle object of "radians" radians (float).
  6284. */
  6285. function Angle(radians) {
  6286. var _this = this;
  6287. /**
  6288. * Returns the Angle value in degrees (float).
  6289. */
  6290. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6291. /**
  6292. * Returns the Angle value in radians (float).
  6293. */
  6294. this.radians = function () { return _this._radians; };
  6295. this._radians = radians;
  6296. if (this._radians < 0.0)
  6297. this._radians += (2.0 * Math.PI);
  6298. }
  6299. /**
  6300. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6301. */
  6302. Angle.BetweenTwoPoints = function (a, b) {
  6303. var delta = b.subtract(a);
  6304. var theta = Math.atan2(delta.y, delta.x);
  6305. return new Angle(theta);
  6306. };
  6307. /**
  6308. * Returns a new Angle object from the passed float in radians.
  6309. */
  6310. Angle.FromRadians = function (radians) {
  6311. return new Angle(radians);
  6312. };
  6313. /**
  6314. * Returns a new Angle object from the passed float in degrees.
  6315. */
  6316. Angle.FromDegrees = function (degrees) {
  6317. return new Angle(degrees * Math.PI / 180.0);
  6318. };
  6319. return Angle;
  6320. }());
  6321. BABYLON.Angle = Angle;
  6322. var Arc2 = /** @class */ (function () {
  6323. /**
  6324. * Creates an Arc object from the three passed points : start, middle and end.
  6325. */
  6326. function Arc2(startPoint, midPoint, endPoint) {
  6327. this.startPoint = startPoint;
  6328. this.midPoint = midPoint;
  6329. this.endPoint = endPoint;
  6330. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6331. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6332. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6333. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6334. 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);
  6335. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6336. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6337. var a1 = this.startAngle.degrees();
  6338. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6339. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6340. // angles correction
  6341. if (a2 - a1 > +180.0)
  6342. a2 -= 360.0;
  6343. if (a2 - a1 < -180.0)
  6344. a2 += 360.0;
  6345. if (a3 - a2 > +180.0)
  6346. a3 -= 360.0;
  6347. if (a3 - a2 < -180.0)
  6348. a3 += 360.0;
  6349. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6350. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6351. }
  6352. return Arc2;
  6353. }());
  6354. BABYLON.Arc2 = Arc2;
  6355. var Path2 = /** @class */ (function () {
  6356. /**
  6357. * Creates a Path2 object from the starting 2D coordinates x and y.
  6358. */
  6359. function Path2(x, y) {
  6360. this._points = new Array();
  6361. this._length = 0.0;
  6362. this.closed = false;
  6363. this._points.push(new Vector2(x, y));
  6364. }
  6365. /**
  6366. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6367. * Returns the updated Path2.
  6368. */
  6369. Path2.prototype.addLineTo = function (x, y) {
  6370. if (this.closed) {
  6371. return this;
  6372. }
  6373. var newPoint = new Vector2(x, y);
  6374. var previousPoint = this._points[this._points.length - 1];
  6375. this._points.push(newPoint);
  6376. this._length += newPoint.subtract(previousPoint).length();
  6377. return this;
  6378. };
  6379. /**
  6380. * 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.
  6381. * Returns the updated Path2.
  6382. */
  6383. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6384. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6385. if (this.closed) {
  6386. return this;
  6387. }
  6388. var startPoint = this._points[this._points.length - 1];
  6389. var midPoint = new Vector2(midX, midY);
  6390. var endPoint = new Vector2(endX, endY);
  6391. var arc = new Arc2(startPoint, midPoint, endPoint);
  6392. var increment = arc.angle.radians() / numberOfSegments;
  6393. if (arc.orientation === Orientation.CW)
  6394. increment *= -1;
  6395. var currentAngle = arc.startAngle.radians() + increment;
  6396. for (var i = 0; i < numberOfSegments; i++) {
  6397. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6398. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6399. this.addLineTo(x, y);
  6400. currentAngle += increment;
  6401. }
  6402. return this;
  6403. };
  6404. /**
  6405. * Closes the Path2.
  6406. * Returns the Path2.
  6407. */
  6408. Path2.prototype.close = function () {
  6409. this.closed = true;
  6410. return this;
  6411. };
  6412. /**
  6413. * Returns the Path2 total length (float).
  6414. */
  6415. Path2.prototype.length = function () {
  6416. var result = this._length;
  6417. if (!this.closed) {
  6418. var lastPoint = this._points[this._points.length - 1];
  6419. var firstPoint = this._points[0];
  6420. result += (firstPoint.subtract(lastPoint).length());
  6421. }
  6422. return result;
  6423. };
  6424. /**
  6425. * Returns the Path2 internal array of points.
  6426. */
  6427. Path2.prototype.getPoints = function () {
  6428. return this._points;
  6429. };
  6430. /**
  6431. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6432. */
  6433. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6434. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6435. return Vector2.Zero();
  6436. }
  6437. var lengthPosition = normalizedLengthPosition * this.length();
  6438. var previousOffset = 0;
  6439. for (var i = 0; i < this._points.length; i++) {
  6440. var j = (i + 1) % this._points.length;
  6441. var a = this._points[i];
  6442. var b = this._points[j];
  6443. var bToA = b.subtract(a);
  6444. var nextOffset = (bToA.length() + previousOffset);
  6445. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6446. var dir = bToA.normalize();
  6447. var localOffset = lengthPosition - previousOffset;
  6448. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6449. }
  6450. previousOffset = nextOffset;
  6451. }
  6452. return Vector2.Zero();
  6453. };
  6454. /**
  6455. * Returns a new Path2 starting at the coordinates (x, y).
  6456. */
  6457. Path2.StartingAt = function (x, y) {
  6458. return new Path2(x, y);
  6459. };
  6460. return Path2;
  6461. }());
  6462. BABYLON.Path2 = Path2;
  6463. var Path3D = /** @class */ (function () {
  6464. /**
  6465. * new Path3D(path, normal, raw)
  6466. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6467. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6468. * path : an array of Vector3, the curve axis of the Path3D
  6469. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6470. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6471. */
  6472. function Path3D(path, firstNormal, raw) {
  6473. if (firstNormal === void 0) { firstNormal = null; }
  6474. this.path = path;
  6475. this._curve = new Array();
  6476. this._distances = new Array();
  6477. this._tangents = new Array();
  6478. this._normals = new Array();
  6479. this._binormals = new Array();
  6480. for (var p = 0; p < path.length; p++) {
  6481. this._curve[p] = path[p].clone(); // hard copy
  6482. }
  6483. this._raw = raw || false;
  6484. this._compute(firstNormal);
  6485. }
  6486. /**
  6487. * Returns the Path3D array of successive Vector3 designing its curve.
  6488. */
  6489. Path3D.prototype.getCurve = function () {
  6490. return this._curve;
  6491. };
  6492. /**
  6493. * Returns an array populated with tangent vectors on each Path3D curve point.
  6494. */
  6495. Path3D.prototype.getTangents = function () {
  6496. return this._tangents;
  6497. };
  6498. /**
  6499. * Returns an array populated with normal vectors on each Path3D curve point.
  6500. */
  6501. Path3D.prototype.getNormals = function () {
  6502. return this._normals;
  6503. };
  6504. /**
  6505. * Returns an array populated with binormal vectors on each Path3D curve point.
  6506. */
  6507. Path3D.prototype.getBinormals = function () {
  6508. return this._binormals;
  6509. };
  6510. /**
  6511. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6512. */
  6513. Path3D.prototype.getDistances = function () {
  6514. return this._distances;
  6515. };
  6516. /**
  6517. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6518. * Returns the same object updated.
  6519. */
  6520. Path3D.prototype.update = function (path, firstNormal) {
  6521. if (firstNormal === void 0) { firstNormal = null; }
  6522. for (var p = 0; p < path.length; p++) {
  6523. this._curve[p].x = path[p].x;
  6524. this._curve[p].y = path[p].y;
  6525. this._curve[p].z = path[p].z;
  6526. }
  6527. this._compute(firstNormal);
  6528. return this;
  6529. };
  6530. // private function compute() : computes tangents, normals and binormals
  6531. Path3D.prototype._compute = function (firstNormal) {
  6532. var l = this._curve.length;
  6533. // first and last tangents
  6534. this._tangents[0] = this._getFirstNonNullVector(0);
  6535. if (!this._raw) {
  6536. this._tangents[0].normalize();
  6537. }
  6538. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6539. if (!this._raw) {
  6540. this._tangents[l - 1].normalize();
  6541. }
  6542. // normals and binormals at first point : arbitrary vector with _normalVector()
  6543. var tg0 = this._tangents[0];
  6544. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6545. this._normals[0] = pp0;
  6546. if (!this._raw) {
  6547. this._normals[0].normalize();
  6548. }
  6549. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6550. if (!this._raw) {
  6551. this._binormals[0].normalize();
  6552. }
  6553. this._distances[0] = 0.0;
  6554. // normals and binormals : next points
  6555. var prev; // previous vector (segment)
  6556. var cur; // current vector (segment)
  6557. var curTang; // current tangent
  6558. // previous normal
  6559. var prevBinor; // previous binormal
  6560. for (var i = 1; i < l; i++) {
  6561. // tangents
  6562. prev = this._getLastNonNullVector(i);
  6563. if (i < l - 1) {
  6564. cur = this._getFirstNonNullVector(i);
  6565. this._tangents[i] = prev.add(cur);
  6566. this._tangents[i].normalize();
  6567. }
  6568. this._distances[i] = this._distances[i - 1] + prev.length();
  6569. // normals and binormals
  6570. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6571. curTang = this._tangents[i];
  6572. prevBinor = this._binormals[i - 1];
  6573. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6574. if (!this._raw) {
  6575. this._normals[i].normalize();
  6576. }
  6577. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6578. if (!this._raw) {
  6579. this._binormals[i].normalize();
  6580. }
  6581. }
  6582. };
  6583. // private function getFirstNonNullVector(index)
  6584. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6585. Path3D.prototype._getFirstNonNullVector = function (index) {
  6586. var i = 1;
  6587. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6588. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6589. i++;
  6590. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6591. }
  6592. return nNVector;
  6593. };
  6594. // private function getLastNonNullVector(index)
  6595. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6596. Path3D.prototype._getLastNonNullVector = function (index) {
  6597. var i = 1;
  6598. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6599. while (nLVector.length() === 0 && index > i + 1) {
  6600. i++;
  6601. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6602. }
  6603. return nLVector;
  6604. };
  6605. // private function normalVector(v0, vt, va) :
  6606. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6607. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6608. Path3D.prototype._normalVector = function (v0, vt, va) {
  6609. var normal0;
  6610. var tgl = vt.length();
  6611. if (tgl === 0.0) {
  6612. tgl = 1.0;
  6613. }
  6614. if (va === undefined || va === null) {
  6615. var point;
  6616. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6617. point = new Vector3(0.0, -1.0, 0.0);
  6618. }
  6619. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6620. point = new Vector3(1.0, 0.0, 0.0);
  6621. }
  6622. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6623. point = new Vector3(0.0, 0.0, 1.0);
  6624. }
  6625. else {
  6626. point = Vector3.Zero();
  6627. }
  6628. normal0 = Vector3.Cross(vt, point);
  6629. }
  6630. else {
  6631. normal0 = Vector3.Cross(vt, va);
  6632. Vector3.CrossToRef(normal0, vt, normal0);
  6633. }
  6634. normal0.normalize();
  6635. return normal0;
  6636. };
  6637. return Path3D;
  6638. }());
  6639. BABYLON.Path3D = Path3D;
  6640. var Curve3 = /** @class */ (function () {
  6641. /**
  6642. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6643. * A Curve3 is designed from a series of successive Vector3.
  6644. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6645. */
  6646. function Curve3(points) {
  6647. this._length = 0.0;
  6648. this._points = points;
  6649. this._length = this._computeLength(points);
  6650. }
  6651. /**
  6652. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6653. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6654. * @param v1 (Vector3) the control point
  6655. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6656. * @param nbPoints (integer) the wanted number of points in the curve
  6657. */
  6658. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6659. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6660. var bez = new Array();
  6661. var equation = function (t, val0, val1, val2) {
  6662. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6663. return res;
  6664. };
  6665. for (var i = 0; i <= nbPoints; i++) {
  6666. 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)));
  6667. }
  6668. return new Curve3(bez);
  6669. };
  6670. /**
  6671. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6672. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6673. * @param v1 (Vector3) the first control point
  6674. * @param v2 (Vector3) the second control point
  6675. * @param v3 (Vector3) the end point of the Cubic Bezier
  6676. * @param nbPoints (integer) the wanted number of points in the curve
  6677. */
  6678. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6679. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6680. var bez = new Array();
  6681. var equation = function (t, val0, val1, val2, val3) {
  6682. 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;
  6683. return res;
  6684. };
  6685. for (var i = 0; i <= nbPoints; i++) {
  6686. 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)));
  6687. }
  6688. return new Curve3(bez);
  6689. };
  6690. /**
  6691. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6692. * @param p1 (Vector3) the origin point of the Hermite Spline
  6693. * @param t1 (Vector3) the tangent vector at the origin point
  6694. * @param p2 (Vector3) the end point of the Hermite Spline
  6695. * @param t2 (Vector3) the tangent vector at the end point
  6696. * @param nbPoints (integer) the wanted number of points in the curve
  6697. */
  6698. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6699. var hermite = new Array();
  6700. var step = 1.0 / nbPoints;
  6701. for (var i = 0; i <= nbPoints; i++) {
  6702. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6703. }
  6704. return new Curve3(hermite);
  6705. };
  6706. /**
  6707. * Returns a Curve3 object along a CatmullRom Spline curve :
  6708. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6709. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6710. */
  6711. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6712. var totalPoints = new Array();
  6713. totalPoints.push(points[0].clone());
  6714. Array.prototype.push.apply(totalPoints, points);
  6715. totalPoints.push(points[points.length - 1].clone());
  6716. var catmullRom = new Array();
  6717. var step = 1.0 / nbPoints;
  6718. var amount = 0.0;
  6719. for (var i = 0; i < totalPoints.length - 3; i++) {
  6720. amount = 0;
  6721. for (var c = 0; c < nbPoints; c++) {
  6722. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6723. amount += step;
  6724. }
  6725. }
  6726. i--;
  6727. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6728. return new Curve3(catmullRom);
  6729. };
  6730. /**
  6731. * Returns the Curve3 stored array of successive Vector3
  6732. */
  6733. Curve3.prototype.getPoints = function () {
  6734. return this._points;
  6735. };
  6736. /**
  6737. * Returns the computed length (float) of the curve.
  6738. */
  6739. Curve3.prototype.length = function () {
  6740. return this._length;
  6741. };
  6742. /**
  6743. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6744. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6745. * curveA and curveB keep unchanged.
  6746. */
  6747. Curve3.prototype.continue = function (curve) {
  6748. var lastPoint = this._points[this._points.length - 1];
  6749. var continuedPoints = this._points.slice();
  6750. var curvePoints = curve.getPoints();
  6751. for (var i = 1; i < curvePoints.length; i++) {
  6752. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6753. }
  6754. var continuedCurve = new Curve3(continuedPoints);
  6755. return continuedCurve;
  6756. };
  6757. Curve3.prototype._computeLength = function (path) {
  6758. var l = 0;
  6759. for (var i = 1; i < path.length; i++) {
  6760. l += (path[i].subtract(path[i - 1])).length();
  6761. }
  6762. return l;
  6763. };
  6764. return Curve3;
  6765. }());
  6766. BABYLON.Curve3 = Curve3;
  6767. // Vertex formats
  6768. var PositionNormalVertex = /** @class */ (function () {
  6769. function PositionNormalVertex(position, normal) {
  6770. if (position === void 0) { position = Vector3.Zero(); }
  6771. if (normal === void 0) { normal = Vector3.Up(); }
  6772. this.position = position;
  6773. this.normal = normal;
  6774. }
  6775. PositionNormalVertex.prototype.clone = function () {
  6776. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6777. };
  6778. return PositionNormalVertex;
  6779. }());
  6780. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6781. var PositionNormalTextureVertex = /** @class */ (function () {
  6782. function PositionNormalTextureVertex(position, normal, uv) {
  6783. if (position === void 0) { position = Vector3.Zero(); }
  6784. if (normal === void 0) { normal = Vector3.Up(); }
  6785. if (uv === void 0) { uv = Vector2.Zero(); }
  6786. this.position = position;
  6787. this.normal = normal;
  6788. this.uv = uv;
  6789. }
  6790. PositionNormalTextureVertex.prototype.clone = function () {
  6791. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6792. };
  6793. return PositionNormalTextureVertex;
  6794. }());
  6795. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6796. // Temporary pre-allocated objects for engine internal use
  6797. // usage in any internal function :
  6798. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6799. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6800. var Tmp = /** @class */ (function () {
  6801. function Tmp() {
  6802. }
  6803. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6804. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6805. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6806. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6807. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6808. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6809. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6810. Matrix.Zero(), Matrix.Zero(),
  6811. Matrix.Zero(), Matrix.Zero(),
  6812. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6813. return Tmp;
  6814. }());
  6815. BABYLON.Tmp = Tmp;
  6816. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6817. var MathTmp = /** @class */ (function () {
  6818. function MathTmp() {
  6819. }
  6820. MathTmp.Vector3 = [Vector3.Zero()];
  6821. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6822. MathTmp.Quaternion = [Quaternion.Zero()];
  6823. return MathTmp;
  6824. }());
  6825. })(BABYLON || (BABYLON = {}));
  6826. //# sourceMappingURL=babylon.math.js.map
  6827. "use strict";
  6828. var BABYLON;
  6829. (function (BABYLON) {
  6830. var Scalar = /** @class */ (function () {
  6831. function Scalar() {
  6832. }
  6833. /**
  6834. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6835. */
  6836. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6837. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6838. var num = a - b;
  6839. return -epsilon <= num && num <= epsilon;
  6840. };
  6841. /**
  6842. * Returns a string : the upper case translation of the number i to hexadecimal.
  6843. */
  6844. Scalar.ToHex = function (i) {
  6845. var str = i.toString(16);
  6846. if (i <= 15) {
  6847. return ("0" + str).toUpperCase();
  6848. }
  6849. return str.toUpperCase();
  6850. };
  6851. /**
  6852. * Returns -1 if value is negative and +1 is value is positive.
  6853. * Returns the value itself if it's equal to zero.
  6854. */
  6855. Scalar.Sign = function (value) {
  6856. value = +value; // convert to a number
  6857. if (value === 0 || isNaN(value))
  6858. return value;
  6859. return value > 0 ? 1 : -1;
  6860. };
  6861. /**
  6862. * Returns the value itself if it's between min and max.
  6863. * Returns min if the value is lower than min.
  6864. * Returns max if the value is greater than max.
  6865. */
  6866. Scalar.Clamp = function (value, min, max) {
  6867. if (min === void 0) { min = 0; }
  6868. if (max === void 0) { max = 1; }
  6869. return Math.min(max, Math.max(min, value));
  6870. };
  6871. /**
  6872. * Returns the log2 of value.
  6873. */
  6874. Scalar.Log2 = function (value) {
  6875. return Math.log(value) * Math.LOG2E;
  6876. };
  6877. /**
  6878. * Loops the value, so that it is never larger than length and never smaller than 0.
  6879. *
  6880. * This is similar to the modulo operator but it works with floating point numbers.
  6881. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6882. * With t = 5 and length = 2.5, the result would be 0.0.
  6883. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6884. */
  6885. Scalar.Repeat = function (value, length) {
  6886. return value - Math.floor(value / length) * length;
  6887. };
  6888. /**
  6889. * Normalize the value between 0.0 and 1.0 using min and max values
  6890. */
  6891. Scalar.Normalize = function (value, min, max) {
  6892. return (value - min) / (max - min);
  6893. };
  6894. /**
  6895. * Denormalize the value from 0.0 and 1.0 using min and max values
  6896. */
  6897. Scalar.Denormalize = function (normalized, min, max) {
  6898. return (normalized * (max - min) + min);
  6899. };
  6900. /**
  6901. * Calculates the shortest difference between two given angles given in degrees.
  6902. */
  6903. Scalar.DeltaAngle = function (current, target) {
  6904. var num = Scalar.Repeat(target - current, 360.0);
  6905. if (num > 180.0) {
  6906. num -= 360.0;
  6907. }
  6908. return num;
  6909. };
  6910. /**
  6911. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6912. *
  6913. * The returned value will move back and forth between 0 and length
  6914. */
  6915. Scalar.PingPong = function (tx, length) {
  6916. var t = Scalar.Repeat(tx, length * 2.0);
  6917. return length - Math.abs(t - length);
  6918. };
  6919. /**
  6920. * Interpolates between min and max with smoothing at the limits.
  6921. *
  6922. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6923. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6924. */
  6925. Scalar.SmoothStep = function (from, to, tx) {
  6926. var t = Scalar.Clamp(tx);
  6927. t = -2.0 * t * t * t + 3.0 * t * t;
  6928. return to * t + from * (1.0 - t);
  6929. };
  6930. /**
  6931. * Moves a value current towards target.
  6932. *
  6933. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6934. * Negative values of maxDelta pushes the value away from target.
  6935. */
  6936. Scalar.MoveTowards = function (current, target, maxDelta) {
  6937. var result = 0;
  6938. if (Math.abs(target - current) <= maxDelta) {
  6939. result = target;
  6940. }
  6941. else {
  6942. result = current + Scalar.Sign(target - current) * maxDelta;
  6943. }
  6944. return result;
  6945. };
  6946. /**
  6947. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6948. *
  6949. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6950. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6951. */
  6952. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6953. var num = Scalar.DeltaAngle(current, target);
  6954. var result = 0;
  6955. if (-maxDelta < num && num < maxDelta) {
  6956. result = target;
  6957. }
  6958. else {
  6959. target = current + num;
  6960. result = Scalar.MoveTowards(current, target, maxDelta);
  6961. }
  6962. return result;
  6963. };
  6964. /**
  6965. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6966. */
  6967. Scalar.Lerp = function (start, end, amount) {
  6968. return start + ((end - start) * amount);
  6969. };
  6970. /**
  6971. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6972. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6973. */
  6974. Scalar.LerpAngle = function (start, end, amount) {
  6975. var num = Scalar.Repeat(end - start, 360.0);
  6976. if (num > 180.0) {
  6977. num -= 360.0;
  6978. }
  6979. return start + num * Scalar.Clamp(amount);
  6980. };
  6981. /**
  6982. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6983. */
  6984. Scalar.InverseLerp = function (a, b, value) {
  6985. var result = 0;
  6986. if (a != b) {
  6987. result = Scalar.Clamp((value - a) / (b - a));
  6988. }
  6989. else {
  6990. result = 0.0;
  6991. }
  6992. return result;
  6993. };
  6994. /**
  6995. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6996. */
  6997. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6998. var squared = amount * amount;
  6999. var cubed = amount * squared;
  7000. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7001. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7002. var part3 = (cubed - (2.0 * squared)) + amount;
  7003. var part4 = cubed - squared;
  7004. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7005. };
  7006. /**
  7007. * Returns a random float number between and min and max values
  7008. */
  7009. Scalar.RandomRange = function (min, max) {
  7010. if (min === max)
  7011. return min;
  7012. return ((Math.random() * (max - min)) + min);
  7013. };
  7014. /**
  7015. * This function returns percentage of a number in a given range.
  7016. *
  7017. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7018. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7019. */
  7020. Scalar.RangeToPercent = function (number, min, max) {
  7021. return ((number - min) / (max - min));
  7022. };
  7023. /**
  7024. * This function returns number that corresponds to the percentage in a given range.
  7025. *
  7026. * PercentToRange(0.34,0,100) will return 34.
  7027. */
  7028. Scalar.PercentToRange = function (percent, min, max) {
  7029. return ((max - min) * percent + min);
  7030. };
  7031. /**
  7032. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7033. * @param angle The angle to normalize in radian.
  7034. * @return The converted angle.
  7035. */
  7036. Scalar.NormalizeRadians = function (angle) {
  7037. // More precise but slower version kept for reference.
  7038. // angle = angle % Tools.TwoPi;
  7039. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7040. //if (angle > Math.PI) {
  7041. // angle -= Tools.TwoPi;
  7042. //}
  7043. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7044. return angle;
  7045. };
  7046. /**
  7047. * Two pi constants convenient for computation.
  7048. */
  7049. Scalar.TwoPi = Math.PI * 2;
  7050. return Scalar;
  7051. }());
  7052. BABYLON.Scalar = Scalar;
  7053. })(BABYLON || (BABYLON = {}));
  7054. //# sourceMappingURL=babylon.math.scalar.js.map
  7055. "use strict";
  7056. //# sourceMappingURL=babylon.mixins.js.map
  7057. "use strict";
  7058. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7059. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7060. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7061. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7062. //# sourceMappingURL=babylon.webgl2.js.map
  7063. "use strict";
  7064. var BABYLON;
  7065. (function (BABYLON) {
  7066. var __decoratorInitialStore = {};
  7067. var __mergedStore = {};
  7068. var _copySource = function (creationFunction, source, instanciate) {
  7069. var destination = creationFunction();
  7070. // Tags
  7071. if (BABYLON.Tags) {
  7072. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7073. }
  7074. var classStore = getMergedStore(destination);
  7075. // Properties
  7076. for (var property in classStore) {
  7077. var propertyDescriptor = classStore[property];
  7078. var sourceProperty = source[property];
  7079. var propertyType = propertyDescriptor.type;
  7080. if (sourceProperty !== undefined && sourceProperty !== null) {
  7081. switch (propertyType) {
  7082. case 0: // Value
  7083. case 6:// Mesh reference
  7084. destination[property] = sourceProperty;
  7085. break;
  7086. case 1:// Texture
  7087. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7088. break;
  7089. case 2: // Color3
  7090. case 3: // FresnelParameters
  7091. case 4: // Vector2
  7092. case 5: // Vector3
  7093. case 7: // Color Curves
  7094. case 10:// Quaternion
  7095. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7096. break;
  7097. }
  7098. }
  7099. }
  7100. return destination;
  7101. };
  7102. function getDirectStore(target) {
  7103. var classKey = target.getClassName();
  7104. if (!__decoratorInitialStore[classKey]) {
  7105. __decoratorInitialStore[classKey] = {};
  7106. }
  7107. return __decoratorInitialStore[classKey];
  7108. }
  7109. /**
  7110. * Return the list of properties flagged as serializable
  7111. * @param target: host object
  7112. */
  7113. function getMergedStore(target) {
  7114. var classKey = target.getClassName();
  7115. if (__mergedStore[classKey]) {
  7116. return __mergedStore[classKey];
  7117. }
  7118. __mergedStore[classKey] = {};
  7119. var store = __mergedStore[classKey];
  7120. var currentTarget = target;
  7121. var currentKey = classKey;
  7122. while (currentKey) {
  7123. var initialStore = __decoratorInitialStore[currentKey];
  7124. for (var property in initialStore) {
  7125. store[property] = initialStore[property];
  7126. }
  7127. var parent_1 = void 0;
  7128. var done = false;
  7129. do {
  7130. parent_1 = Object.getPrototypeOf(currentTarget);
  7131. if (!parent_1.getClassName) {
  7132. done = true;
  7133. break;
  7134. }
  7135. if (parent_1.getClassName() !== currentKey) {
  7136. break;
  7137. }
  7138. currentTarget = parent_1;
  7139. } while (parent_1);
  7140. if (done) {
  7141. break;
  7142. }
  7143. currentKey = parent_1.getClassName();
  7144. currentTarget = parent_1;
  7145. }
  7146. return store;
  7147. }
  7148. function generateSerializableMember(type, sourceName) {
  7149. return function (target, propertyKey) {
  7150. var classStore = getDirectStore(target);
  7151. if (!classStore[propertyKey]) {
  7152. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7153. }
  7154. };
  7155. }
  7156. function generateExpandMember(setCallback, targetKey) {
  7157. if (targetKey === void 0) { targetKey = null; }
  7158. return function (target, propertyKey) {
  7159. var key = targetKey || ("_" + propertyKey);
  7160. Object.defineProperty(target, propertyKey, {
  7161. get: function () {
  7162. return this[key];
  7163. },
  7164. set: function (value) {
  7165. if (this[key] === value) {
  7166. return;
  7167. }
  7168. this[key] = value;
  7169. target[setCallback].apply(this);
  7170. },
  7171. enumerable: true,
  7172. configurable: true
  7173. });
  7174. };
  7175. }
  7176. function expandToProperty(callback, targetKey) {
  7177. if (targetKey === void 0) { targetKey = null; }
  7178. return generateExpandMember(callback, targetKey);
  7179. }
  7180. BABYLON.expandToProperty = expandToProperty;
  7181. function serialize(sourceName) {
  7182. return generateSerializableMember(0, sourceName); // value member
  7183. }
  7184. BABYLON.serialize = serialize;
  7185. function serializeAsTexture(sourceName) {
  7186. return generateSerializableMember(1, sourceName); // texture member
  7187. }
  7188. BABYLON.serializeAsTexture = serializeAsTexture;
  7189. function serializeAsColor3(sourceName) {
  7190. return generateSerializableMember(2, sourceName); // color3 member
  7191. }
  7192. BABYLON.serializeAsColor3 = serializeAsColor3;
  7193. function serializeAsFresnelParameters(sourceName) {
  7194. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7195. }
  7196. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7197. function serializeAsVector2(sourceName) {
  7198. return generateSerializableMember(4, sourceName); // vector2 member
  7199. }
  7200. BABYLON.serializeAsVector2 = serializeAsVector2;
  7201. function serializeAsVector3(sourceName) {
  7202. return generateSerializableMember(5, sourceName); // vector3 member
  7203. }
  7204. BABYLON.serializeAsVector3 = serializeAsVector3;
  7205. function serializeAsMeshReference(sourceName) {
  7206. return generateSerializableMember(6, sourceName); // mesh reference member
  7207. }
  7208. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7209. function serializeAsColorCurves(sourceName) {
  7210. return generateSerializableMember(7, sourceName); // color curves
  7211. }
  7212. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7213. function serializeAsColor4(sourceName) {
  7214. return generateSerializableMember(8, sourceName); // color 4
  7215. }
  7216. BABYLON.serializeAsColor4 = serializeAsColor4;
  7217. function serializeAsImageProcessingConfiguration(sourceName) {
  7218. return generateSerializableMember(9, sourceName); // image processing
  7219. }
  7220. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7221. function serializeAsQuaternion(sourceName) {
  7222. return generateSerializableMember(10, sourceName); // quaternion member
  7223. }
  7224. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7225. var SerializationHelper = /** @class */ (function () {
  7226. function SerializationHelper() {
  7227. }
  7228. SerializationHelper.Serialize = function (entity, serializationObject) {
  7229. if (!serializationObject) {
  7230. serializationObject = {};
  7231. }
  7232. // Tags
  7233. if (BABYLON.Tags) {
  7234. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7235. }
  7236. var serializedProperties = getMergedStore(entity);
  7237. // Properties
  7238. for (var property in serializedProperties) {
  7239. var propertyDescriptor = serializedProperties[property];
  7240. var targetPropertyName = propertyDescriptor.sourceName || property;
  7241. var propertyType = propertyDescriptor.type;
  7242. var sourceProperty = entity[property];
  7243. if (sourceProperty !== undefined && sourceProperty !== null) {
  7244. switch (propertyType) {
  7245. case 0:// Value
  7246. serializationObject[targetPropertyName] = sourceProperty;
  7247. break;
  7248. case 1:// Texture
  7249. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7250. break;
  7251. case 2:// Color3
  7252. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7253. break;
  7254. case 3:// FresnelParameters
  7255. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7256. break;
  7257. case 4:// Vector2
  7258. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7259. break;
  7260. case 5:// Vector3
  7261. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7262. break;
  7263. case 6:// Mesh reference
  7264. serializationObject[targetPropertyName] = sourceProperty.id;
  7265. break;
  7266. case 7:// Color Curves
  7267. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7268. break;
  7269. case 8:// Color 4
  7270. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7271. break;
  7272. case 9:// Image Processing
  7273. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7274. break;
  7275. }
  7276. }
  7277. }
  7278. return serializationObject;
  7279. };
  7280. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7281. if (rootUrl === void 0) { rootUrl = null; }
  7282. var destination = creationFunction();
  7283. if (!rootUrl) {
  7284. rootUrl = "";
  7285. }
  7286. // Tags
  7287. if (BABYLON.Tags) {
  7288. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7289. }
  7290. var classStore = getMergedStore(destination);
  7291. // Properties
  7292. for (var property in classStore) {
  7293. var propertyDescriptor = classStore[property];
  7294. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7295. var propertyType = propertyDescriptor.type;
  7296. if (sourceProperty !== undefined && sourceProperty !== null) {
  7297. var dest = destination;
  7298. switch (propertyType) {
  7299. case 0:// Value
  7300. dest[property] = sourceProperty;
  7301. break;
  7302. case 1:// Texture
  7303. if (scene) {
  7304. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7305. }
  7306. break;
  7307. case 2:// Color3
  7308. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7309. break;
  7310. case 3:// FresnelParameters
  7311. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7312. break;
  7313. case 4:// Vector2
  7314. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7315. break;
  7316. case 5:// Vector3
  7317. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7318. break;
  7319. case 6:// Mesh reference
  7320. if (scene) {
  7321. dest[property] = scene.getLastMeshByID(sourceProperty);
  7322. }
  7323. break;
  7324. case 7:// Color Curves
  7325. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7326. break;
  7327. case 8:// Color 4
  7328. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7329. break;
  7330. case 9:// Image Processing
  7331. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7332. break;
  7333. }
  7334. }
  7335. }
  7336. return destination;
  7337. };
  7338. SerializationHelper.Clone = function (creationFunction, source) {
  7339. return _copySource(creationFunction, source, false);
  7340. };
  7341. SerializationHelper.Instanciate = function (creationFunction, source) {
  7342. return _copySource(creationFunction, source, true);
  7343. };
  7344. return SerializationHelper;
  7345. }());
  7346. BABYLON.SerializationHelper = SerializationHelper;
  7347. })(BABYLON || (BABYLON = {}));
  7348. //# sourceMappingURL=babylon.decorators.js.map
  7349. "use strict";
  7350. var BABYLON;
  7351. (function (BABYLON) {
  7352. /**
  7353. * Wrapper class for promise with external resolve and reject.
  7354. */
  7355. var Deferred = /** @class */ (function () {
  7356. /**
  7357. * Constructor for this deferred object.
  7358. */
  7359. function Deferred() {
  7360. var _this = this;
  7361. this.promise = new Promise(function (resolve, reject) {
  7362. _this._resolve = resolve;
  7363. _this._reject = reject;
  7364. });
  7365. }
  7366. Object.defineProperty(Deferred.prototype, "resolve", {
  7367. /**
  7368. * The resolve method of the promise associated with this deferred object.
  7369. */
  7370. get: function () {
  7371. return this._resolve;
  7372. },
  7373. enumerable: true,
  7374. configurable: true
  7375. });
  7376. Object.defineProperty(Deferred.prototype, "reject", {
  7377. /**
  7378. * The reject method of the promise associated with this deferred object.
  7379. */
  7380. get: function () {
  7381. return this._reject;
  7382. },
  7383. enumerable: true,
  7384. configurable: true
  7385. });
  7386. return Deferred;
  7387. }());
  7388. BABYLON.Deferred = Deferred;
  7389. })(BABYLON || (BABYLON = {}));
  7390. //# sourceMappingURL=babylon.deferred.js.map
  7391. "use strict";
  7392. var BABYLON;
  7393. (function (BABYLON) {
  7394. /**
  7395. * A class serves as a medium between the observable and its observers
  7396. */
  7397. var EventState = /** @class */ (function () {
  7398. /**
  7399. * Create a new EventState
  7400. * @param mask defines the mask associated with this state
  7401. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7402. * @param target defines the original target of the state
  7403. * @param currentTarget defines the current target of the state
  7404. */
  7405. function EventState(mask, skipNextObservers, target, currentTarget) {
  7406. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7407. this.initalize(mask, skipNextObservers, target, currentTarget);
  7408. }
  7409. /**
  7410. * Initialize the current event state
  7411. * @param mask defines the mask associated with this state
  7412. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7413. * @param target defines the original target of the state
  7414. * @param currentTarget defines the current target of the state
  7415. * @returns the current event state
  7416. */
  7417. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7418. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7419. this.mask = mask;
  7420. this.skipNextObservers = skipNextObservers;
  7421. this.target = target;
  7422. this.currentTarget = currentTarget;
  7423. return this;
  7424. };
  7425. return EventState;
  7426. }());
  7427. BABYLON.EventState = EventState;
  7428. /**
  7429. * Represent an Observer registered to a given Observable object.
  7430. */
  7431. var Observer = /** @class */ (function () {
  7432. /**
  7433. * Creates a new observer
  7434. * @param callback defines the callback to call when the observer is notified
  7435. * @param mask defines the mask of the observer (used to filter notifications)
  7436. * @param scope defines the current scope used to restore the JS context
  7437. */
  7438. function Observer(
  7439. /**
  7440. * Defines the callback to call when the observer is notified
  7441. */
  7442. callback,
  7443. /**
  7444. * Defines the mask of the observer (used to filter notifications)
  7445. */
  7446. mask,
  7447. /**
  7448. * Defines the current scope used to restore the JS context
  7449. */
  7450. scope) {
  7451. if (scope === void 0) { scope = null; }
  7452. this.callback = callback;
  7453. this.mask = mask;
  7454. this.scope = scope;
  7455. /** @ignore */
  7456. this._willBeUnregistered = false;
  7457. /**
  7458. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7459. */
  7460. this.unregisterOnNextCall = false;
  7461. }
  7462. return Observer;
  7463. }());
  7464. BABYLON.Observer = Observer;
  7465. /**
  7466. * Represent a list of observers registered to multiple Observables object.
  7467. */
  7468. var MultiObserver = /** @class */ (function () {
  7469. function MultiObserver() {
  7470. }
  7471. /**
  7472. * Release associated resources
  7473. */
  7474. MultiObserver.prototype.dispose = function () {
  7475. if (this._observers && this._observables) {
  7476. for (var index = 0; index < this._observers.length; index++) {
  7477. this._observables[index].remove(this._observers[index]);
  7478. }
  7479. }
  7480. this._observers = null;
  7481. this._observables = null;
  7482. };
  7483. /**
  7484. * Raise a callback when one of the observable will notify
  7485. * @param observables defines a list of observables to watch
  7486. * @param callback defines the callback to call on notification
  7487. * @param mask defines the mask used to filter notifications
  7488. * @param scope defines the current scope used to restore the JS context
  7489. * @returns the new MultiObserver
  7490. */
  7491. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7492. if (mask === void 0) { mask = -1; }
  7493. if (scope === void 0) { scope = null; }
  7494. var result = new MultiObserver();
  7495. result._observers = new Array();
  7496. result._observables = observables;
  7497. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7498. var observable = observables_1[_i];
  7499. var observer = observable.add(callback, mask, false, scope);
  7500. if (observer) {
  7501. result._observers.push(observer);
  7502. }
  7503. }
  7504. return result;
  7505. };
  7506. return MultiObserver;
  7507. }());
  7508. BABYLON.MultiObserver = MultiObserver;
  7509. /**
  7510. * The Observable class is a simple implementation of the Observable pattern.
  7511. * 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.
  7512. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7513. * 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).
  7514. * 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.
  7515. */
  7516. var Observable = /** @class */ (function () {
  7517. /**
  7518. * Creates a new observable
  7519. * @param onObserverAdded defines a callback to call when a new observer is added
  7520. */
  7521. function Observable(onObserverAdded) {
  7522. this._observers = new Array();
  7523. this._eventState = new EventState(0);
  7524. if (onObserverAdded) {
  7525. this._onObserverAdded = onObserverAdded;
  7526. }
  7527. }
  7528. /**
  7529. * Create a new Observer with the specified callback
  7530. * @param callback the callback that will be executed for that Observer
  7531. * @param mask the mask used to filter observers
  7532. * @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.
  7533. * @param scope optional scope for the callback to be called from
  7534. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7535. * @returns the new observer created for the callback
  7536. */
  7537. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7538. if (mask === void 0) { mask = -1; }
  7539. if (insertFirst === void 0) { insertFirst = false; }
  7540. if (scope === void 0) { scope = null; }
  7541. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7542. if (!callback) {
  7543. return null;
  7544. }
  7545. var observer = new Observer(callback, mask, scope);
  7546. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7547. if (insertFirst) {
  7548. this._observers.unshift(observer);
  7549. }
  7550. else {
  7551. this._observers.push(observer);
  7552. }
  7553. if (this._onObserverAdded) {
  7554. this._onObserverAdded(observer);
  7555. }
  7556. return observer;
  7557. };
  7558. /**
  7559. * Remove an Observer from the Observable object
  7560. * @param observer the instance of the Observer to remove
  7561. * @returns false if it doesn't belong to this Observable
  7562. */
  7563. Observable.prototype.remove = function (observer) {
  7564. if (!observer) {
  7565. return false;
  7566. }
  7567. var index = this._observers.indexOf(observer);
  7568. if (index !== -1) {
  7569. this._observers.splice(index, 1);
  7570. return true;
  7571. }
  7572. return false;
  7573. };
  7574. /**
  7575. * Remove a callback from the Observable object
  7576. * @param callback the callback to remove
  7577. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7578. * @returns false if it doesn't belong to this Observable
  7579. */
  7580. Observable.prototype.removeCallback = function (callback, scope) {
  7581. for (var index = 0; index < this._observers.length; index++) {
  7582. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7583. this._observers.splice(index, 1);
  7584. return true;
  7585. }
  7586. }
  7587. return false;
  7588. };
  7589. Observable.prototype._deferUnregister = function (observer) {
  7590. var _this = this;
  7591. observer.unregisterOnNextCall = false;
  7592. observer._willBeUnregistered = true;
  7593. BABYLON.Tools.SetImmediate(function () {
  7594. _this.remove(observer);
  7595. });
  7596. };
  7597. /**
  7598. * Notify all Observers by calling their respective callback with the given data
  7599. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7600. * @param eventData defines the data to send to all observers
  7601. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7602. * @param target defines the original target of the state
  7603. * @param currentTarget defines the current target of the state
  7604. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7605. */
  7606. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7607. if (mask === void 0) { mask = -1; }
  7608. if (!this._observers.length) {
  7609. return true;
  7610. }
  7611. var state = this._eventState;
  7612. state.mask = mask;
  7613. state.target = target;
  7614. state.currentTarget = currentTarget;
  7615. state.skipNextObservers = false;
  7616. state.lastReturnValue = eventData;
  7617. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7618. var obs = _a[_i];
  7619. if (obs._willBeUnregistered) {
  7620. continue;
  7621. }
  7622. if (obs.mask & mask) {
  7623. if (obs.scope) {
  7624. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7625. }
  7626. else {
  7627. state.lastReturnValue = obs.callback(eventData, state);
  7628. }
  7629. if (obs.unregisterOnNextCall) {
  7630. this._deferUnregister(obs);
  7631. }
  7632. }
  7633. if (state.skipNextObservers) {
  7634. return false;
  7635. }
  7636. }
  7637. return true;
  7638. };
  7639. /**
  7640. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7641. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7642. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7643. * and it is crucial that all callbacks will be executed.
  7644. * The order of the callbacks is kept, callbacks are not executed parallel.
  7645. *
  7646. * @param eventData The data to be sent to each callback
  7647. * @param mask is used to filter observers defaults to -1
  7648. * @param target defines the callback target (see EventState)
  7649. * @param currentTarget defines he current object in the bubbling phase
  7650. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7651. */
  7652. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7653. var _this = this;
  7654. if (mask === void 0) { mask = -1; }
  7655. // create an empty promise
  7656. var p = Promise.resolve(eventData);
  7657. // no observers? return this promise.
  7658. if (!this._observers.length) {
  7659. return p;
  7660. }
  7661. var state = this._eventState;
  7662. state.mask = mask;
  7663. state.target = target;
  7664. state.currentTarget = currentTarget;
  7665. state.skipNextObservers = false;
  7666. // execute one callback after another (not using Promise.all, the order is important)
  7667. this._observers.forEach(function (obs) {
  7668. if (state.skipNextObservers) {
  7669. return;
  7670. }
  7671. if (obs._willBeUnregistered) {
  7672. return;
  7673. }
  7674. if (obs.mask & mask) {
  7675. if (obs.scope) {
  7676. p = p.then(function (lastReturnedValue) {
  7677. state.lastReturnValue = lastReturnedValue;
  7678. return obs.callback.apply(obs.scope, [eventData, state]);
  7679. });
  7680. }
  7681. else {
  7682. p = p.then(function (lastReturnedValue) {
  7683. state.lastReturnValue = lastReturnedValue;
  7684. return obs.callback(eventData, state);
  7685. });
  7686. }
  7687. if (obs.unregisterOnNextCall) {
  7688. _this._deferUnregister(obs);
  7689. }
  7690. }
  7691. });
  7692. // return the eventData
  7693. return p.then(function () { return eventData; });
  7694. };
  7695. /**
  7696. * Notify a specific observer
  7697. * @param observer defines the observer to notify
  7698. * @param eventData defines the data to be sent to each callback
  7699. * @param mask is used to filter observers defaults to -1
  7700. */
  7701. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7702. if (mask === void 0) { mask = -1; }
  7703. var state = this._eventState;
  7704. state.mask = mask;
  7705. state.skipNextObservers = false;
  7706. observer.callback(eventData, state);
  7707. };
  7708. /**
  7709. * Gets a boolean indicating if the observable has at least one observer
  7710. * @returns true is the Observable has at least one Observer registered
  7711. */
  7712. Observable.prototype.hasObservers = function () {
  7713. return this._observers.length > 0;
  7714. };
  7715. /**
  7716. * Clear the list of observers
  7717. */
  7718. Observable.prototype.clear = function () {
  7719. this._observers = new Array();
  7720. this._onObserverAdded = null;
  7721. };
  7722. /**
  7723. * Clone the current observable
  7724. * @returns a new observable
  7725. */
  7726. Observable.prototype.clone = function () {
  7727. var result = new Observable();
  7728. result._observers = this._observers.slice(0);
  7729. return result;
  7730. };
  7731. /**
  7732. * Does this observable handles observer registered with a given mask
  7733. * @param mask defines the mask to be tested
  7734. * @return whether or not one observer registered with the given mask is handeled
  7735. **/
  7736. Observable.prototype.hasSpecificMask = function (mask) {
  7737. if (mask === void 0) { mask = -1; }
  7738. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7739. var obs = _a[_i];
  7740. if (obs.mask & mask || obs.mask === mask) {
  7741. return true;
  7742. }
  7743. }
  7744. return false;
  7745. };
  7746. return Observable;
  7747. }());
  7748. BABYLON.Observable = Observable;
  7749. })(BABYLON || (BABYLON = {}));
  7750. //# sourceMappingURL=babylon.observable.js.map
  7751. "use strict";
  7752. var BABYLON;
  7753. (function (BABYLON) {
  7754. var SmartArray = /** @class */ (function () {
  7755. function SmartArray(capacity) {
  7756. this.length = 0;
  7757. this.data = new Array(capacity);
  7758. this._id = SmartArray._GlobalId++;
  7759. }
  7760. SmartArray.prototype.push = function (value) {
  7761. this.data[this.length++] = value;
  7762. if (this.length > this.data.length) {
  7763. this.data.length *= 2;
  7764. }
  7765. };
  7766. SmartArray.prototype.forEach = function (func) {
  7767. for (var index = 0; index < this.length; index++) {
  7768. func(this.data[index]);
  7769. }
  7770. };
  7771. SmartArray.prototype.sort = function (compareFn) {
  7772. this.data.sort(compareFn);
  7773. };
  7774. SmartArray.prototype.reset = function () {
  7775. this.length = 0;
  7776. };
  7777. SmartArray.prototype.dispose = function () {
  7778. this.reset();
  7779. if (this.data) {
  7780. this.data.length = 0;
  7781. this.data = [];
  7782. }
  7783. };
  7784. SmartArray.prototype.concat = function (array) {
  7785. if (array.length === 0) {
  7786. return;
  7787. }
  7788. if (this.length + array.length > this.data.length) {
  7789. this.data.length = (this.length + array.length) * 2;
  7790. }
  7791. for (var index = 0; index < array.length; index++) {
  7792. this.data[this.length++] = (array.data || array)[index];
  7793. }
  7794. };
  7795. SmartArray.prototype.indexOf = function (value) {
  7796. var position = this.data.indexOf(value);
  7797. if (position >= this.length) {
  7798. return -1;
  7799. }
  7800. return position;
  7801. };
  7802. SmartArray.prototype.contains = function (value) {
  7803. return this.data.indexOf(value) !== -1;
  7804. };
  7805. // Statics
  7806. SmartArray._GlobalId = 0;
  7807. return SmartArray;
  7808. }());
  7809. BABYLON.SmartArray = SmartArray;
  7810. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7811. __extends(SmartArrayNoDuplicate, _super);
  7812. function SmartArrayNoDuplicate() {
  7813. var _this = _super !== null && _super.apply(this, arguments) || this;
  7814. _this._duplicateId = 0;
  7815. return _this;
  7816. }
  7817. SmartArrayNoDuplicate.prototype.push = function (value) {
  7818. _super.prototype.push.call(this, value);
  7819. if (!value.__smartArrayFlags) {
  7820. value.__smartArrayFlags = {};
  7821. }
  7822. value.__smartArrayFlags[this._id] = this._duplicateId;
  7823. };
  7824. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7825. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7826. return false;
  7827. }
  7828. this.push(value);
  7829. return true;
  7830. };
  7831. SmartArrayNoDuplicate.prototype.reset = function () {
  7832. _super.prototype.reset.call(this);
  7833. this._duplicateId++;
  7834. };
  7835. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7836. if (array.length === 0) {
  7837. return;
  7838. }
  7839. if (this.length + array.length > this.data.length) {
  7840. this.data.length = (this.length + array.length) * 2;
  7841. }
  7842. for (var index = 0; index < array.length; index++) {
  7843. var item = (array.data || array)[index];
  7844. this.pushNoDuplicate(item);
  7845. }
  7846. };
  7847. return SmartArrayNoDuplicate;
  7848. }(SmartArray));
  7849. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7850. })(BABYLON || (BABYLON = {}));
  7851. //# sourceMappingURL=babylon.smartArray.js.map
  7852. "use strict";
  7853. var BABYLON;
  7854. (function (BABYLON) {
  7855. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7856. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7857. var LoadFileError = /** @class */ (function (_super) {
  7858. __extends(LoadFileError, _super);
  7859. function LoadFileError(message, request) {
  7860. var _this = _super.call(this, message) || this;
  7861. _this.request = request;
  7862. _this.name = "LoadFileError";
  7863. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7864. return _this;
  7865. }
  7866. // Polyfill for Object.setPrototypeOf if necessary.
  7867. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7868. return LoadFileError;
  7869. }(Error));
  7870. BABYLON.LoadFileError = LoadFileError;
  7871. var RetryStrategy = /** @class */ (function () {
  7872. function RetryStrategy() {
  7873. }
  7874. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7875. if (maxRetries === void 0) { maxRetries = 3; }
  7876. if (baseInterval === void 0) { baseInterval = 500; }
  7877. return function (url, request, retryIndex) {
  7878. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7879. return -1;
  7880. }
  7881. return Math.pow(2, retryIndex) * baseInterval;
  7882. };
  7883. };
  7884. return RetryStrategy;
  7885. }());
  7886. BABYLON.RetryStrategy = RetryStrategy;
  7887. // Screenshots
  7888. var screenshotCanvas;
  7889. var cloneValue = function (source, destinationObject) {
  7890. if (!source)
  7891. return null;
  7892. if (source instanceof BABYLON.Mesh) {
  7893. return null;
  7894. }
  7895. if (source instanceof BABYLON.SubMesh) {
  7896. return source.clone(destinationObject);
  7897. }
  7898. else if (source.clone) {
  7899. return source.clone();
  7900. }
  7901. return null;
  7902. };
  7903. var Tools = /** @class */ (function () {
  7904. function Tools() {
  7905. }
  7906. /**
  7907. * Interpolates between a and b via alpha
  7908. * @param a The lower value (returned when alpha = 0)
  7909. * @param b The upper value (returned when alpha = 1)
  7910. * @param alpha The interpolation-factor
  7911. * @return The mixed value
  7912. */
  7913. Tools.Mix = function (a, b, alpha) {
  7914. return a * (1 - alpha) + b * alpha;
  7915. };
  7916. Tools.Instantiate = function (className) {
  7917. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7918. return Tools.RegisteredExternalClasses[className];
  7919. }
  7920. var arr = className.split(".");
  7921. var fn = (window || this);
  7922. for (var i = 0, len = arr.length; i < len; i++) {
  7923. fn = fn[arr[i]];
  7924. }
  7925. if (typeof fn !== "function") {
  7926. return null;
  7927. }
  7928. return fn;
  7929. };
  7930. /**
  7931. * Provides a slice function that will work even on IE
  7932. * @param data defines the array to slice
  7933. * @returns the new sliced array
  7934. */
  7935. Tools.Slice = function (data) {
  7936. if (data.slice) {
  7937. return data.slice();
  7938. }
  7939. return Array.prototype.slice.call(data);
  7940. };
  7941. Tools.SetImmediate = function (action) {
  7942. if (window.setImmediate) {
  7943. window.setImmediate(action);
  7944. }
  7945. else {
  7946. setTimeout(action, 1);
  7947. }
  7948. };
  7949. Tools.IsExponentOfTwo = function (value) {
  7950. var count = 1;
  7951. do {
  7952. count *= 2;
  7953. } while (count < value);
  7954. return count === value;
  7955. };
  7956. /**
  7957. * Find the next highest power of two.
  7958. * @param x Number to start search from.
  7959. * @return Next highest power of two.
  7960. */
  7961. Tools.CeilingPOT = function (x) {
  7962. x--;
  7963. x |= x >> 1;
  7964. x |= x >> 2;
  7965. x |= x >> 4;
  7966. x |= x >> 8;
  7967. x |= x >> 16;
  7968. x++;
  7969. return x;
  7970. };
  7971. /**
  7972. * Find the next lowest power of two.
  7973. * @param x Number to start search from.
  7974. * @return Next lowest power of two.
  7975. */
  7976. Tools.FloorPOT = function (x) {
  7977. x = x | (x >> 1);
  7978. x = x | (x >> 2);
  7979. x = x | (x >> 4);
  7980. x = x | (x >> 8);
  7981. x = x | (x >> 16);
  7982. return x - (x >> 1);
  7983. };
  7984. /**
  7985. * Find the nearest power of two.
  7986. * @param x Number to start search from.
  7987. * @return Next nearest power of two.
  7988. */
  7989. Tools.NearestPOT = function (x) {
  7990. var c = Tools.CeilingPOT(x);
  7991. var f = Tools.FloorPOT(x);
  7992. return (c - x) > (x - f) ? f : c;
  7993. };
  7994. Tools.GetExponentOfTwo = function (value, max, mode) {
  7995. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7996. var pot;
  7997. switch (mode) {
  7998. case BABYLON.Engine.SCALEMODE_FLOOR:
  7999. pot = Tools.FloorPOT(value);
  8000. break;
  8001. case BABYLON.Engine.SCALEMODE_NEAREST:
  8002. pot = Tools.NearestPOT(value);
  8003. break;
  8004. case BABYLON.Engine.SCALEMODE_CEILING:
  8005. default:
  8006. pot = Tools.CeilingPOT(value);
  8007. break;
  8008. }
  8009. return Math.min(pot, max);
  8010. };
  8011. Tools.GetFilename = function (path) {
  8012. var index = path.lastIndexOf("/");
  8013. if (index < 0)
  8014. return path;
  8015. return path.substring(index + 1);
  8016. };
  8017. /**
  8018. * Extracts the "folder" part of a path (everything before the filename).
  8019. * @param uri The URI to extract the info from
  8020. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8021. * @returns The "folder" part of the path
  8022. */
  8023. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8024. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8025. var index = uri.lastIndexOf("/");
  8026. if (index < 0) {
  8027. if (returnUnchangedIfNoSlash) {
  8028. return uri;
  8029. }
  8030. return "";
  8031. }
  8032. return uri.substring(0, index + 1);
  8033. };
  8034. Tools.GetDOMTextContent = function (element) {
  8035. var result = "";
  8036. var child = element.firstChild;
  8037. while (child) {
  8038. if (child.nodeType === 3) {
  8039. result += child.textContent;
  8040. }
  8041. child = child.nextSibling;
  8042. }
  8043. return result;
  8044. };
  8045. Tools.ToDegrees = function (angle) {
  8046. return angle * 180 / Math.PI;
  8047. };
  8048. Tools.ToRadians = function (angle) {
  8049. return angle * Math.PI / 180;
  8050. };
  8051. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8052. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8053. var output = "";
  8054. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8055. var i = 0;
  8056. var bytes = new Uint8Array(buffer);
  8057. while (i < bytes.length) {
  8058. chr1 = bytes[i++];
  8059. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8060. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8061. enc1 = chr1 >> 2;
  8062. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8063. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8064. enc4 = chr3 & 63;
  8065. if (isNaN(chr2)) {
  8066. enc3 = enc4 = 64;
  8067. }
  8068. else if (isNaN(chr3)) {
  8069. enc4 = 64;
  8070. }
  8071. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8072. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8073. }
  8074. return "data:image/png;base64," + output;
  8075. };
  8076. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8077. if (bias === void 0) { bias = null; }
  8078. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8079. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8080. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8081. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8082. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8083. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8084. }
  8085. if (bias) {
  8086. minimum.x -= minimum.x * bias.x + bias.y;
  8087. minimum.y -= minimum.y * bias.x + bias.y;
  8088. minimum.z -= minimum.z * bias.x + bias.y;
  8089. maximum.x += maximum.x * bias.x + bias.y;
  8090. maximum.y += maximum.y * bias.x + bias.y;
  8091. maximum.z += maximum.z * bias.x + bias.y;
  8092. }
  8093. return {
  8094. minimum: minimum,
  8095. maximum: maximum
  8096. };
  8097. };
  8098. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8099. if (bias === void 0) { bias = null; }
  8100. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8101. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8102. if (!stride) {
  8103. stride = 3;
  8104. }
  8105. for (var index = start; index < start + count; index++) {
  8106. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8107. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8108. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8109. }
  8110. if (bias) {
  8111. minimum.x -= minimum.x * bias.x + bias.y;
  8112. minimum.y -= minimum.y * bias.x + bias.y;
  8113. minimum.z -= minimum.z * bias.x + bias.y;
  8114. maximum.x += maximum.x * bias.x + bias.y;
  8115. maximum.y += maximum.y * bias.x + bias.y;
  8116. maximum.z += maximum.z * bias.x + bias.y;
  8117. }
  8118. return {
  8119. minimum: minimum,
  8120. maximum: maximum
  8121. };
  8122. };
  8123. Tools.Vector2ArrayFeeder = function (array) {
  8124. return function (index) {
  8125. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8126. var length = isFloatArray ? array.length / 2 : array.length;
  8127. if (index >= length) {
  8128. return null;
  8129. }
  8130. if (isFloatArray) {
  8131. var fa = array;
  8132. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8133. }
  8134. var a = array;
  8135. return a[index];
  8136. };
  8137. };
  8138. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8139. if (bias === void 0) { bias = null; }
  8140. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8141. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8142. var i = 0;
  8143. var cur = feeder(i++);
  8144. while (cur) {
  8145. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8146. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8147. cur = feeder(i++);
  8148. }
  8149. if (bias) {
  8150. minimum.x -= minimum.x * bias.x + bias.y;
  8151. minimum.y -= minimum.y * bias.x + bias.y;
  8152. maximum.x += maximum.x * bias.x + bias.y;
  8153. maximum.y += maximum.y * bias.x + bias.y;
  8154. }
  8155. return {
  8156. minimum: minimum,
  8157. maximum: maximum
  8158. };
  8159. };
  8160. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8161. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8162. return null;
  8163. return Array.isArray(obj) ? obj : [obj];
  8164. };
  8165. // Misc.
  8166. Tools.GetPointerPrefix = function () {
  8167. var eventPrefix = "pointer";
  8168. // Check if pointer events are supported
  8169. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8170. eventPrefix = "mouse";
  8171. }
  8172. return eventPrefix;
  8173. };
  8174. /**
  8175. * @param func - the function to be called
  8176. * @param requester - the object that will request the next frame. Falls back to window.
  8177. */
  8178. Tools.QueueNewFrame = function (func, requester) {
  8179. if (!Tools.IsWindowObjectExist()) {
  8180. return setTimeout(func, 16);
  8181. }
  8182. if (!requester) {
  8183. requester = window;
  8184. }
  8185. if (requester.requestAnimationFrame) {
  8186. return requester.requestAnimationFrame(func);
  8187. }
  8188. else if (requester.msRequestAnimationFrame) {
  8189. return requester.msRequestAnimationFrame(func);
  8190. }
  8191. else if (requester.webkitRequestAnimationFrame) {
  8192. return requester.webkitRequestAnimationFrame(func);
  8193. }
  8194. else if (requester.mozRequestAnimationFrame) {
  8195. return requester.mozRequestAnimationFrame(func);
  8196. }
  8197. else if (requester.oRequestAnimationFrame) {
  8198. return requester.oRequestAnimationFrame(func);
  8199. }
  8200. else {
  8201. return window.setTimeout(func, 16);
  8202. }
  8203. };
  8204. Tools.RequestFullscreen = function (element) {
  8205. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8206. if (!requestFunction)
  8207. return;
  8208. requestFunction.call(element);
  8209. };
  8210. Tools.ExitFullscreen = function () {
  8211. if (document.exitFullscreen) {
  8212. document.exitFullscreen();
  8213. }
  8214. else if (document.mozCancelFullScreen) {
  8215. document.mozCancelFullScreen();
  8216. }
  8217. else if (document.webkitCancelFullScreen) {
  8218. document.webkitCancelFullScreen();
  8219. }
  8220. else if (document.msCancelFullScreen) {
  8221. document.msCancelFullScreen();
  8222. }
  8223. };
  8224. Tools.SetCorsBehavior = function (url, element) {
  8225. if (url && url.indexOf("data:") === 0) {
  8226. return;
  8227. }
  8228. if (Tools.CorsBehavior) {
  8229. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8230. element.crossOrigin = Tools.CorsBehavior;
  8231. }
  8232. else {
  8233. var result = Tools.CorsBehavior(url);
  8234. if (result) {
  8235. element.crossOrigin = result;
  8236. }
  8237. }
  8238. }
  8239. };
  8240. // External files
  8241. Tools.CleanUrl = function (url) {
  8242. url = url.replace(/#/mg, "%23");
  8243. return url;
  8244. };
  8245. Tools.LoadImage = function (url, onLoad, onError, database) {
  8246. if (url instanceof ArrayBuffer) {
  8247. url = Tools.EncodeArrayBufferTobase64(url);
  8248. }
  8249. url = Tools.CleanUrl(url);
  8250. url = Tools.PreprocessUrl(url);
  8251. var img = new Image();
  8252. Tools.SetCorsBehavior(url, img);
  8253. var loadHandler = function () {
  8254. img.removeEventListener("load", loadHandler);
  8255. img.removeEventListener("error", errorHandler);
  8256. onLoad(img);
  8257. };
  8258. var errorHandler = function (err) {
  8259. img.removeEventListener("load", loadHandler);
  8260. img.removeEventListener("error", errorHandler);
  8261. Tools.Error("Error while trying to load image: " + url);
  8262. if (onError) {
  8263. onError("Error while trying to load image: " + url, err);
  8264. }
  8265. };
  8266. img.addEventListener("load", loadHandler);
  8267. img.addEventListener("error", errorHandler);
  8268. var noIndexedDB = function () {
  8269. img.src = url;
  8270. };
  8271. var loadFromIndexedDB = function () {
  8272. if (database) {
  8273. database.loadImageFromDB(url, img);
  8274. }
  8275. };
  8276. //ANY database to do!
  8277. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8278. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8279. }
  8280. else {
  8281. if (url.indexOf("file:") !== -1) {
  8282. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8283. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8284. try {
  8285. var blobURL;
  8286. try {
  8287. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8288. }
  8289. catch (ex) {
  8290. // Chrome doesn't support oneTimeOnly parameter
  8291. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8292. }
  8293. img.src = blobURL;
  8294. }
  8295. catch (e) {
  8296. img.src = "";
  8297. }
  8298. return img;
  8299. }
  8300. }
  8301. noIndexedDB();
  8302. }
  8303. return img;
  8304. };
  8305. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8306. url = Tools.CleanUrl(url);
  8307. url = Tools.PreprocessUrl(url);
  8308. // If file and file input are set
  8309. if (url.indexOf("file:") !== -1) {
  8310. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8311. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8312. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8313. }
  8314. }
  8315. var loadUrl = Tools.BaseUrl + url;
  8316. var aborted = false;
  8317. var fileRequest = {
  8318. onCompleteObservable: new BABYLON.Observable(),
  8319. abort: function () { return aborted = true; },
  8320. };
  8321. var requestFile = function () {
  8322. var request = new XMLHttpRequest();
  8323. var retryHandle = null;
  8324. fileRequest.abort = function () {
  8325. aborted = true;
  8326. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8327. request.abort();
  8328. }
  8329. if (retryHandle !== null) {
  8330. clearTimeout(retryHandle);
  8331. retryHandle = null;
  8332. }
  8333. };
  8334. var retryLoop = function (retryIndex) {
  8335. request.open('GET', loadUrl, true);
  8336. if (useArrayBuffer) {
  8337. request.responseType = "arraybuffer";
  8338. }
  8339. if (onProgress) {
  8340. request.addEventListener("progress", onProgress);
  8341. }
  8342. var onLoadEnd = function () {
  8343. request.removeEventListener("loadend", onLoadEnd);
  8344. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8345. fileRequest.onCompleteObservable.clear();
  8346. };
  8347. request.addEventListener("loadend", onLoadEnd);
  8348. var onReadyStateChange = function () {
  8349. if (aborted) {
  8350. return;
  8351. }
  8352. // In case of undefined state in some browsers.
  8353. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8354. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8355. request.removeEventListener("readystatechange", onReadyStateChange);
  8356. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8357. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8358. return;
  8359. }
  8360. var retryStrategy = Tools.DefaultRetryStrategy;
  8361. if (retryStrategy) {
  8362. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8363. if (waitTime !== -1) {
  8364. // Prevent the request from completing for retry.
  8365. request.removeEventListener("loadend", onLoadEnd);
  8366. request = new XMLHttpRequest();
  8367. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8368. return;
  8369. }
  8370. }
  8371. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8372. if (onError) {
  8373. onError(request, e);
  8374. }
  8375. else {
  8376. throw e;
  8377. }
  8378. }
  8379. };
  8380. request.addEventListener("readystatechange", onReadyStateChange);
  8381. request.send();
  8382. };
  8383. retryLoop(0);
  8384. };
  8385. // Caching all files
  8386. if (database && database.enableSceneOffline) {
  8387. var noIndexedDB_1 = function () {
  8388. if (!aborted) {
  8389. requestFile();
  8390. }
  8391. };
  8392. var loadFromIndexedDB = function () {
  8393. // TODO: database needs to support aborting and should return a IFileRequest
  8394. if (aborted) {
  8395. return;
  8396. }
  8397. if (database) {
  8398. database.loadFileFromDB(url, function (data) {
  8399. if (!aborted) {
  8400. onSuccess(data);
  8401. }
  8402. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8403. }, onProgress ? function (event) {
  8404. if (!aborted) {
  8405. onProgress(event);
  8406. }
  8407. } : undefined, noIndexedDB_1, useArrayBuffer);
  8408. }
  8409. };
  8410. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8411. }
  8412. else {
  8413. requestFile();
  8414. }
  8415. return fileRequest;
  8416. };
  8417. /**
  8418. * Load a script (identified by an url). When the url returns, the
  8419. * content of this file is added into a new script element, attached to the DOM (body element)
  8420. */
  8421. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8422. var head = document.getElementsByTagName('head')[0];
  8423. var script = document.createElement('script');
  8424. script.type = 'text/javascript';
  8425. script.src = scriptUrl;
  8426. script.onload = function () {
  8427. if (onSuccess) {
  8428. onSuccess();
  8429. }
  8430. };
  8431. script.onerror = function (e) {
  8432. if (onError) {
  8433. onError("Unable to load script", e);
  8434. }
  8435. };
  8436. head.appendChild(script);
  8437. };
  8438. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8439. var reader = new FileReader();
  8440. var request = {
  8441. onCompleteObservable: new BABYLON.Observable(),
  8442. abort: function () { return reader.abort(); },
  8443. };
  8444. reader.onloadend = function (e) {
  8445. request.onCompleteObservable.notifyObservers(request);
  8446. };
  8447. reader.onload = function (e) {
  8448. //target doesn't have result from ts 1.3
  8449. callback(e.target['result']);
  8450. };
  8451. reader.onprogress = progressCallback;
  8452. reader.readAsDataURL(fileToLoad);
  8453. return request;
  8454. };
  8455. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8456. var reader = new FileReader();
  8457. var request = {
  8458. onCompleteObservable: new BABYLON.Observable(),
  8459. abort: function () { return reader.abort(); },
  8460. };
  8461. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8462. reader.onerror = function (e) {
  8463. Tools.Log("Error while reading file: " + fileToLoad.name);
  8464. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8465. };
  8466. reader.onload = function (e) {
  8467. //target doesn't have result from ts 1.3
  8468. callback(e.target['result']);
  8469. };
  8470. if (progressCallBack) {
  8471. reader.onprogress = progressCallBack;
  8472. }
  8473. if (!useArrayBuffer) {
  8474. // Asynchronous read
  8475. reader.readAsText(fileToLoad);
  8476. }
  8477. else {
  8478. reader.readAsArrayBuffer(fileToLoad);
  8479. }
  8480. return request;
  8481. };
  8482. //returns a downloadable url to a file content.
  8483. Tools.FileAsURL = function (content) {
  8484. var fileBlob = new Blob([content]);
  8485. var url = window.URL || window.webkitURL;
  8486. var link = url.createObjectURL(fileBlob);
  8487. return link;
  8488. };
  8489. // Misc.
  8490. Tools.Format = function (value, decimals) {
  8491. if (decimals === void 0) { decimals = 2; }
  8492. return value.toFixed(decimals);
  8493. };
  8494. Tools.CheckExtends = function (v, min, max) {
  8495. if (v.x < min.x)
  8496. min.x = v.x;
  8497. if (v.y < min.y)
  8498. min.y = v.y;
  8499. if (v.z < min.z)
  8500. min.z = v.z;
  8501. if (v.x > max.x)
  8502. max.x = v.x;
  8503. if (v.y > max.y)
  8504. max.y = v.y;
  8505. if (v.z > max.z)
  8506. max.z = v.z;
  8507. };
  8508. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8509. for (var prop in source) {
  8510. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8511. continue;
  8512. }
  8513. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8514. continue;
  8515. }
  8516. var sourceValue = source[prop];
  8517. var typeOfSourceValue = typeof sourceValue;
  8518. if (typeOfSourceValue === "function") {
  8519. continue;
  8520. }
  8521. try {
  8522. if (typeOfSourceValue === "object") {
  8523. if (sourceValue instanceof Array) {
  8524. destination[prop] = [];
  8525. if (sourceValue.length > 0) {
  8526. if (typeof sourceValue[0] == "object") {
  8527. for (var index = 0; index < sourceValue.length; index++) {
  8528. var clonedValue = cloneValue(sourceValue[index], destination);
  8529. if (destination[prop].indexOf(clonedValue) === -1) {
  8530. destination[prop].push(clonedValue);
  8531. }
  8532. }
  8533. }
  8534. else {
  8535. destination[prop] = sourceValue.slice(0);
  8536. }
  8537. }
  8538. }
  8539. else {
  8540. destination[prop] = cloneValue(sourceValue, destination);
  8541. }
  8542. }
  8543. else {
  8544. destination[prop] = sourceValue;
  8545. }
  8546. }
  8547. catch (e) {
  8548. // Just ignore error (it could be because of a read-only property)
  8549. }
  8550. }
  8551. };
  8552. Tools.IsEmpty = function (obj) {
  8553. for (var i in obj) {
  8554. if (obj.hasOwnProperty(i)) {
  8555. return false;
  8556. }
  8557. }
  8558. return true;
  8559. };
  8560. Tools.RegisterTopRootEvents = function (events) {
  8561. for (var index = 0; index < events.length; index++) {
  8562. var event = events[index];
  8563. window.addEventListener(event.name, event.handler, false);
  8564. try {
  8565. if (window.parent) {
  8566. window.parent.addEventListener(event.name, event.handler, false);
  8567. }
  8568. }
  8569. catch (e) {
  8570. // Silently fails...
  8571. }
  8572. }
  8573. };
  8574. Tools.UnregisterTopRootEvents = function (events) {
  8575. for (var index = 0; index < events.length; index++) {
  8576. var event = events[index];
  8577. window.removeEventListener(event.name, event.handler);
  8578. try {
  8579. if (window.parent) {
  8580. window.parent.removeEventListener(event.name, event.handler);
  8581. }
  8582. }
  8583. catch (e) {
  8584. // Silently fails...
  8585. }
  8586. }
  8587. };
  8588. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8589. if (mimeType === void 0) { mimeType = "image/png"; }
  8590. // Read the contents of the framebuffer
  8591. var numberOfChannelsByLine = width * 4;
  8592. var halfHeight = height / 2;
  8593. //Reading datas from WebGL
  8594. var data = engine.readPixels(0, 0, width, height);
  8595. //To flip image on Y axis.
  8596. for (var i = 0; i < halfHeight; i++) {
  8597. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8598. var currentCell = j + i * numberOfChannelsByLine;
  8599. var targetLine = height - i - 1;
  8600. var targetCell = j + targetLine * numberOfChannelsByLine;
  8601. var temp = data[currentCell];
  8602. data[currentCell] = data[targetCell];
  8603. data[targetCell] = temp;
  8604. }
  8605. }
  8606. // Create a 2D canvas to store the result
  8607. if (!screenshotCanvas) {
  8608. screenshotCanvas = document.createElement('canvas');
  8609. }
  8610. screenshotCanvas.width = width;
  8611. screenshotCanvas.height = height;
  8612. var context = screenshotCanvas.getContext('2d');
  8613. if (context) {
  8614. // Copy the pixels to a 2D canvas
  8615. var imageData = context.createImageData(width, height);
  8616. var castData = (imageData.data);
  8617. castData.set(data);
  8618. context.putImageData(imageData, 0, 0);
  8619. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8620. }
  8621. };
  8622. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8623. if (mimeType === void 0) { mimeType = "image/png"; }
  8624. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8625. if (successCallback) {
  8626. successCallback(base64Image);
  8627. }
  8628. else {
  8629. // We need HTMLCanvasElement.toBlob for HD screenshots
  8630. if (!screenshotCanvas.toBlob) {
  8631. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8632. screenshotCanvas.toBlob = function (callback, type, quality) {
  8633. var _this = this;
  8634. setTimeout(function () {
  8635. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8636. for (var i = 0; i < len; i++) {
  8637. arr[i] = binStr.charCodeAt(i);
  8638. }
  8639. callback(new Blob([arr], { type: type || 'image/png' }));
  8640. });
  8641. };
  8642. }
  8643. screenshotCanvas.toBlob(function (blob) {
  8644. var url = URL.createObjectURL(blob);
  8645. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8646. if (("download" in document.createElement("a"))) {
  8647. var a = window.document.createElement("a");
  8648. a.href = url;
  8649. if (fileName) {
  8650. a.setAttribute("download", fileName);
  8651. }
  8652. else {
  8653. var date = new Date();
  8654. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8655. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8656. }
  8657. window.document.body.appendChild(a);
  8658. a.addEventListener("click", function () {
  8659. if (a.parentElement) {
  8660. a.parentElement.removeChild(a);
  8661. }
  8662. });
  8663. a.click();
  8664. }
  8665. else {
  8666. var newWindow = window.open("");
  8667. if (!newWindow)
  8668. return;
  8669. var img = newWindow.document.createElement("img");
  8670. img.onload = function () {
  8671. // no longer need to read the blob so it's revoked
  8672. URL.revokeObjectURL(url);
  8673. };
  8674. img.src = url;
  8675. newWindow.document.body.appendChild(img);
  8676. }
  8677. });
  8678. }
  8679. };
  8680. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8681. if (mimeType === void 0) { mimeType = "image/png"; }
  8682. var width;
  8683. var height;
  8684. // If a precision value is specified
  8685. if (size.precision) {
  8686. width = Math.round(engine.getRenderWidth() * size.precision);
  8687. height = Math.round(width / engine.getAspectRatio(camera));
  8688. }
  8689. else if (size.width && size.height) {
  8690. width = size.width;
  8691. height = size.height;
  8692. }
  8693. else if (size.width && !size.height) {
  8694. width = size.width;
  8695. height = Math.round(width / engine.getAspectRatio(camera));
  8696. }
  8697. else if (size.height && !size.width) {
  8698. height = size.height;
  8699. width = Math.round(height * engine.getAspectRatio(camera));
  8700. }
  8701. else if (!isNaN(size)) {
  8702. height = size;
  8703. width = size;
  8704. }
  8705. else {
  8706. Tools.Error("Invalid 'size' parameter !");
  8707. return;
  8708. }
  8709. if (!screenshotCanvas) {
  8710. screenshotCanvas = document.createElement('canvas');
  8711. }
  8712. screenshotCanvas.width = width;
  8713. screenshotCanvas.height = height;
  8714. var renderContext = screenshotCanvas.getContext("2d");
  8715. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8716. var newWidth = width;
  8717. var newHeight = newWidth / ratio;
  8718. if (newHeight > height) {
  8719. newHeight = height;
  8720. newWidth = newHeight * ratio;
  8721. }
  8722. var offsetX = Math.max(0, width - newWidth) / 2;
  8723. var offsetY = Math.max(0, height - newHeight) / 2;
  8724. var renderingCanvas = engine.getRenderingCanvas();
  8725. if (renderContext && renderingCanvas) {
  8726. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8727. }
  8728. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8729. };
  8730. /**
  8731. * Generates an image screenshot from the specified camera.
  8732. *
  8733. * @param engine The engine to use for rendering
  8734. * @param camera The camera to use for rendering
  8735. * @param size This parameter can be set to a single number or to an object with the
  8736. * following (optional) properties: precision, width, height. If a single number is passed,
  8737. * it will be used for both width and height. If an object is passed, the screenshot size
  8738. * will be derived from the parameters. The precision property is a multiplier allowing
  8739. * rendering at a higher or lower resolution.
  8740. * @param successCallback The callback receives a single parameter which contains the
  8741. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8742. * src parameter of an <img> to display it.
  8743. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8744. * Check your browser for supported MIME types.
  8745. * @param samples Texture samples (default: 1)
  8746. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8747. * @param fileName A name for for the downloaded file.
  8748. * @constructor
  8749. */
  8750. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8751. if (mimeType === void 0) { mimeType = "image/png"; }
  8752. if (samples === void 0) { samples = 1; }
  8753. if (antialiasing === void 0) { antialiasing = false; }
  8754. var width;
  8755. var height;
  8756. //If a precision value is specified
  8757. if (size.precision) {
  8758. width = Math.round(engine.getRenderWidth() * size.precision);
  8759. height = Math.round(width / engine.getAspectRatio(camera));
  8760. size = { width: width, height: height };
  8761. }
  8762. else if (size.width && size.height) {
  8763. width = size.width;
  8764. height = size.height;
  8765. }
  8766. else if (size.width && !size.height) {
  8767. width = size.width;
  8768. height = Math.round(width / engine.getAspectRatio(camera));
  8769. size = { width: width, height: height };
  8770. }
  8771. else if (size.height && !size.width) {
  8772. height = size.height;
  8773. width = Math.round(height * engine.getAspectRatio(camera));
  8774. size = { width: width, height: height };
  8775. }
  8776. else if (!isNaN(size)) {
  8777. height = size;
  8778. width = size;
  8779. }
  8780. else {
  8781. Tools.Error("Invalid 'size' parameter !");
  8782. return;
  8783. }
  8784. var scene = camera.getScene();
  8785. var previousCamera = null;
  8786. if (scene.activeCamera !== camera) {
  8787. previousCamera = scene.activeCamera;
  8788. scene.activeCamera = camera;
  8789. }
  8790. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8791. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8792. texture.renderList = null;
  8793. texture.samples = samples;
  8794. if (antialiasing) {
  8795. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8796. }
  8797. texture.onAfterRenderObservable.add(function () {
  8798. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8799. });
  8800. scene.incrementRenderId();
  8801. scene.resetCachedMaterial();
  8802. texture.render(true);
  8803. texture.dispose();
  8804. if (previousCamera) {
  8805. scene.activeCamera = previousCamera;
  8806. }
  8807. camera.getProjectionMatrix(true); // Force cache refresh;
  8808. };
  8809. // XHR response validator for local file scenario
  8810. Tools.ValidateXHRData = function (xhr, dataType) {
  8811. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8812. if (dataType === void 0) { dataType = 7; }
  8813. try {
  8814. if (dataType & 1) {
  8815. if (xhr.responseText && xhr.responseText.length > 0) {
  8816. return true;
  8817. }
  8818. else if (dataType === 1) {
  8819. return false;
  8820. }
  8821. }
  8822. if (dataType & 2) {
  8823. // Check header width and height since there is no "TGA" magic number
  8824. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8825. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8826. return true;
  8827. }
  8828. else if (dataType === 2) {
  8829. return false;
  8830. }
  8831. }
  8832. if (dataType & 4) {
  8833. // Check for the "DDS" magic number
  8834. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8835. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8836. return true;
  8837. }
  8838. else {
  8839. return false;
  8840. }
  8841. }
  8842. }
  8843. catch (e) {
  8844. // Global protection
  8845. }
  8846. return false;
  8847. };
  8848. /**
  8849. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8850. * Be aware Math.random() could cause collisions, but:
  8851. * "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"
  8852. */
  8853. Tools.RandomId = function () {
  8854. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8855. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8856. return v.toString(16);
  8857. });
  8858. };
  8859. /**
  8860. * Test if the given uri is a base64 string.
  8861. * @param uri The uri to test
  8862. * @return True if the uri is a base64 string or false otherwise.
  8863. */
  8864. Tools.IsBase64 = function (uri) {
  8865. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8866. };
  8867. /**
  8868. * Decode the given base64 uri.
  8869. * @param uri The uri to decode
  8870. * @return The decoded base64 data.
  8871. */
  8872. Tools.DecodeBase64 = function (uri) {
  8873. var decodedString = atob(uri.split(",")[1]);
  8874. var bufferLength = decodedString.length;
  8875. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8876. for (var i = 0; i < bufferLength; i++) {
  8877. bufferView[i] = decodedString.charCodeAt(i);
  8878. }
  8879. return bufferView.buffer;
  8880. };
  8881. Object.defineProperty(Tools, "NoneLogLevel", {
  8882. get: function () {
  8883. return Tools._NoneLogLevel;
  8884. },
  8885. enumerable: true,
  8886. configurable: true
  8887. });
  8888. Object.defineProperty(Tools, "MessageLogLevel", {
  8889. get: function () {
  8890. return Tools._MessageLogLevel;
  8891. },
  8892. enumerable: true,
  8893. configurable: true
  8894. });
  8895. Object.defineProperty(Tools, "WarningLogLevel", {
  8896. get: function () {
  8897. return Tools._WarningLogLevel;
  8898. },
  8899. enumerable: true,
  8900. configurable: true
  8901. });
  8902. Object.defineProperty(Tools, "ErrorLogLevel", {
  8903. get: function () {
  8904. return Tools._ErrorLogLevel;
  8905. },
  8906. enumerable: true,
  8907. configurable: true
  8908. });
  8909. Object.defineProperty(Tools, "AllLogLevel", {
  8910. get: function () {
  8911. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8912. },
  8913. enumerable: true,
  8914. configurable: true
  8915. });
  8916. Tools._AddLogEntry = function (entry) {
  8917. Tools._LogCache = entry + Tools._LogCache;
  8918. if (Tools.OnNewCacheEntry) {
  8919. Tools.OnNewCacheEntry(entry);
  8920. }
  8921. };
  8922. Tools._FormatMessage = function (message) {
  8923. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8924. var date = new Date();
  8925. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8926. };
  8927. Tools._LogDisabled = function (message) {
  8928. // nothing to do
  8929. };
  8930. Tools._LogEnabled = function (message) {
  8931. var formattedMessage = Tools._FormatMessage(message);
  8932. console.log("BJS - " + formattedMessage);
  8933. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8934. Tools._AddLogEntry(entry);
  8935. };
  8936. Tools._WarnDisabled = function (message) {
  8937. // nothing to do
  8938. };
  8939. Tools._WarnEnabled = function (message) {
  8940. var formattedMessage = Tools._FormatMessage(message);
  8941. console.warn("BJS - " + formattedMessage);
  8942. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8943. Tools._AddLogEntry(entry);
  8944. };
  8945. Tools._ErrorDisabled = function (message) {
  8946. // nothing to do
  8947. };
  8948. Tools._ErrorEnabled = function (message) {
  8949. Tools.errorsCount++;
  8950. var formattedMessage = Tools._FormatMessage(message);
  8951. console.error("BJS - " + formattedMessage);
  8952. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8953. Tools._AddLogEntry(entry);
  8954. };
  8955. Object.defineProperty(Tools, "LogCache", {
  8956. get: function () {
  8957. return Tools._LogCache;
  8958. },
  8959. enumerable: true,
  8960. configurable: true
  8961. });
  8962. Tools.ClearLogCache = function () {
  8963. Tools._LogCache = "";
  8964. Tools.errorsCount = 0;
  8965. };
  8966. Object.defineProperty(Tools, "LogLevels", {
  8967. set: function (level) {
  8968. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8969. Tools.Log = Tools._LogEnabled;
  8970. }
  8971. else {
  8972. Tools.Log = Tools._LogDisabled;
  8973. }
  8974. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8975. Tools.Warn = Tools._WarnEnabled;
  8976. }
  8977. else {
  8978. Tools.Warn = Tools._WarnDisabled;
  8979. }
  8980. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8981. Tools.Error = Tools._ErrorEnabled;
  8982. }
  8983. else {
  8984. Tools.Error = Tools._ErrorDisabled;
  8985. }
  8986. },
  8987. enumerable: true,
  8988. configurable: true
  8989. });
  8990. Tools.IsWindowObjectExist = function () {
  8991. return (typeof window) !== "undefined";
  8992. };
  8993. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8994. get: function () {
  8995. return Tools._PerformanceNoneLogLevel;
  8996. },
  8997. enumerable: true,
  8998. configurable: true
  8999. });
  9000. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9001. get: function () {
  9002. return Tools._PerformanceUserMarkLogLevel;
  9003. },
  9004. enumerable: true,
  9005. configurable: true
  9006. });
  9007. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9008. get: function () {
  9009. return Tools._PerformanceConsoleLogLevel;
  9010. },
  9011. enumerable: true,
  9012. configurable: true
  9013. });
  9014. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9015. set: function (level) {
  9016. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9017. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9018. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9019. return;
  9020. }
  9021. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9022. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9023. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9024. return;
  9025. }
  9026. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9027. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9028. },
  9029. enumerable: true,
  9030. configurable: true
  9031. });
  9032. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9033. };
  9034. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9035. };
  9036. Tools._StartUserMark = function (counterName, condition) {
  9037. if (condition === void 0) { condition = true; }
  9038. if (!Tools._performance) {
  9039. if (!Tools.IsWindowObjectExist()) {
  9040. return;
  9041. }
  9042. Tools._performance = window.performance;
  9043. }
  9044. if (!condition || !Tools._performance.mark) {
  9045. return;
  9046. }
  9047. Tools._performance.mark(counterName + "-Begin");
  9048. };
  9049. Tools._EndUserMark = function (counterName, condition) {
  9050. if (condition === void 0) { condition = true; }
  9051. if (!condition || !Tools._performance.mark) {
  9052. return;
  9053. }
  9054. Tools._performance.mark(counterName + "-End");
  9055. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9056. };
  9057. Tools._StartPerformanceConsole = function (counterName, condition) {
  9058. if (condition === void 0) { condition = true; }
  9059. if (!condition) {
  9060. return;
  9061. }
  9062. Tools._StartUserMark(counterName, condition);
  9063. if (console.time) {
  9064. console.time(counterName);
  9065. }
  9066. };
  9067. Tools._EndPerformanceConsole = function (counterName, condition) {
  9068. if (condition === void 0) { condition = true; }
  9069. if (!condition) {
  9070. return;
  9071. }
  9072. Tools._EndUserMark(counterName, condition);
  9073. if (console.time) {
  9074. console.timeEnd(counterName);
  9075. }
  9076. };
  9077. Object.defineProperty(Tools, "Now", {
  9078. get: function () {
  9079. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9080. return window.performance.now();
  9081. }
  9082. return new Date().getTime();
  9083. },
  9084. enumerable: true,
  9085. configurable: true
  9086. });
  9087. /**
  9088. * This method will return the name of the class used to create the instance of the given object.
  9089. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9090. * @param object the object to get the class name from
  9091. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9092. */
  9093. Tools.GetClassName = function (object, isType) {
  9094. if (isType === void 0) { isType = false; }
  9095. var name = null;
  9096. if (!isType && object.getClassName) {
  9097. name = object.getClassName();
  9098. }
  9099. else {
  9100. if (object instanceof Object) {
  9101. var classObj = isType ? object : Object.getPrototypeOf(object);
  9102. name = classObj.constructor["__bjsclassName__"];
  9103. }
  9104. if (!name) {
  9105. name = typeof object;
  9106. }
  9107. }
  9108. return name;
  9109. };
  9110. Tools.First = function (array, predicate) {
  9111. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9112. var el = array_1[_i];
  9113. if (predicate(el)) {
  9114. return el;
  9115. }
  9116. }
  9117. return null;
  9118. };
  9119. /**
  9120. * This method will return the name of the full name of the class, including its owning module (if any).
  9121. * 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).
  9122. * @param object the object to get the class name from
  9123. * @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.
  9124. */
  9125. Tools.getFullClassName = function (object, isType) {
  9126. if (isType === void 0) { isType = false; }
  9127. var className = null;
  9128. var moduleName = null;
  9129. if (!isType && object.getClassName) {
  9130. className = object.getClassName();
  9131. }
  9132. else {
  9133. if (object instanceof Object) {
  9134. var classObj = isType ? object : Object.getPrototypeOf(object);
  9135. className = classObj.constructor["__bjsclassName__"];
  9136. moduleName = classObj.constructor["__bjsmoduleName__"];
  9137. }
  9138. if (!className) {
  9139. className = typeof object;
  9140. }
  9141. }
  9142. if (!className) {
  9143. return null;
  9144. }
  9145. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9146. };
  9147. /**
  9148. * 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.
  9149. * @param array
  9150. */
  9151. Tools.arrayOrStringFeeder = function (array) {
  9152. return function (index) {
  9153. if (index >= array.length) {
  9154. return null;
  9155. }
  9156. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9157. if (val && val.getHashCode) {
  9158. val = val.getHashCode();
  9159. }
  9160. if (typeof val === "string") {
  9161. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9162. }
  9163. return val;
  9164. };
  9165. };
  9166. /**
  9167. * Compute the hashCode of a stream of number
  9168. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9169. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9170. * @return the hash code computed
  9171. */
  9172. Tools.hashCodeFromStream = function (feeder) {
  9173. // Based from here: http://stackoverflow.com/a/7616484/802124
  9174. var hash = 0;
  9175. var index = 0;
  9176. var chr = feeder(index++);
  9177. while (chr != null) {
  9178. hash = ((hash << 5) - hash) + chr;
  9179. hash |= 0; // Convert to 32bit integer
  9180. chr = feeder(index++);
  9181. }
  9182. return hash;
  9183. };
  9184. /**
  9185. * Returns a promise that resolves after the given amount of time.
  9186. * @param delay Number of milliseconds to delay
  9187. * @returns Promise that resolves after the given amount of time
  9188. */
  9189. Tools.DelayAsync = function (delay) {
  9190. return new Promise(function (resolve) {
  9191. setTimeout(function () {
  9192. resolve();
  9193. }, delay);
  9194. });
  9195. };
  9196. Tools.BaseUrl = "";
  9197. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9198. /**
  9199. * Default behaviour for cors in the application.
  9200. * It can be a string if the expected behavior is identical in the entire app.
  9201. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9202. */
  9203. Tools.CorsBehavior = "anonymous";
  9204. Tools.UseFallbackTexture = true;
  9205. /**
  9206. * Use this object to register external classes like custom textures or material
  9207. * to allow the laoders to instantiate them
  9208. */
  9209. Tools.RegisteredExternalClasses = {};
  9210. // Used in case of a texture loading problem
  9211. 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";
  9212. Tools.PreprocessUrl = function (url) {
  9213. return url;
  9214. };
  9215. // Logs
  9216. Tools._NoneLogLevel = 0;
  9217. Tools._MessageLogLevel = 1;
  9218. Tools._WarningLogLevel = 2;
  9219. Tools._ErrorLogLevel = 4;
  9220. Tools._LogCache = "";
  9221. Tools.errorsCount = 0;
  9222. Tools.Log = Tools._LogEnabled;
  9223. Tools.Warn = Tools._WarnEnabled;
  9224. Tools.Error = Tools._ErrorEnabled;
  9225. // Performances
  9226. Tools._PerformanceNoneLogLevel = 0;
  9227. Tools._PerformanceUserMarkLogLevel = 1;
  9228. Tools._PerformanceConsoleLogLevel = 2;
  9229. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9230. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9231. return Tools;
  9232. }());
  9233. BABYLON.Tools = Tools;
  9234. /**
  9235. * This class is used to track a performance counter which is number based.
  9236. * The user has access to many properties which give statistics of different nature
  9237. *
  9238. * The implementer can track two kinds of Performance Counter: time and count
  9239. * 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.
  9240. * 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.
  9241. */
  9242. var PerfCounter = /** @class */ (function () {
  9243. function PerfCounter() {
  9244. this._startMonitoringTime = 0;
  9245. this._min = 0;
  9246. this._max = 0;
  9247. this._average = 0;
  9248. this._lastSecAverage = 0;
  9249. this._current = 0;
  9250. this._totalValueCount = 0;
  9251. this._totalAccumulated = 0;
  9252. this._lastSecAccumulated = 0;
  9253. this._lastSecTime = 0;
  9254. this._lastSecValueCount = 0;
  9255. }
  9256. Object.defineProperty(PerfCounter.prototype, "min", {
  9257. /**
  9258. * Returns the smallest value ever
  9259. */
  9260. get: function () {
  9261. return this._min;
  9262. },
  9263. enumerable: true,
  9264. configurable: true
  9265. });
  9266. Object.defineProperty(PerfCounter.prototype, "max", {
  9267. /**
  9268. * Returns the biggest value ever
  9269. */
  9270. get: function () {
  9271. return this._max;
  9272. },
  9273. enumerable: true,
  9274. configurable: true
  9275. });
  9276. Object.defineProperty(PerfCounter.prototype, "average", {
  9277. /**
  9278. * Returns the average value since the performance counter is running
  9279. */
  9280. get: function () {
  9281. return this._average;
  9282. },
  9283. enumerable: true,
  9284. configurable: true
  9285. });
  9286. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9287. /**
  9288. * Returns the average value of the last second the counter was monitored
  9289. */
  9290. get: function () {
  9291. return this._lastSecAverage;
  9292. },
  9293. enumerable: true,
  9294. configurable: true
  9295. });
  9296. Object.defineProperty(PerfCounter.prototype, "current", {
  9297. /**
  9298. * Returns the current value
  9299. */
  9300. get: function () {
  9301. return this._current;
  9302. },
  9303. enumerable: true,
  9304. configurable: true
  9305. });
  9306. Object.defineProperty(PerfCounter.prototype, "total", {
  9307. get: function () {
  9308. return this._totalAccumulated;
  9309. },
  9310. enumerable: true,
  9311. configurable: true
  9312. });
  9313. Object.defineProperty(PerfCounter.prototype, "count", {
  9314. get: function () {
  9315. return this._totalValueCount;
  9316. },
  9317. enumerable: true,
  9318. configurable: true
  9319. });
  9320. /**
  9321. * Call this method to start monitoring a new frame.
  9322. * 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.
  9323. */
  9324. PerfCounter.prototype.fetchNewFrame = function () {
  9325. this._totalValueCount++;
  9326. this._current = 0;
  9327. this._lastSecValueCount++;
  9328. };
  9329. /**
  9330. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9331. * @param newCount the count value to add to the monitored count
  9332. * @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.
  9333. */
  9334. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9335. if (!PerfCounter.Enabled) {
  9336. return;
  9337. }
  9338. this._current += newCount;
  9339. if (fetchResult) {
  9340. this._fetchResult();
  9341. }
  9342. };
  9343. /**
  9344. * Start monitoring this performance counter
  9345. */
  9346. PerfCounter.prototype.beginMonitoring = function () {
  9347. if (!PerfCounter.Enabled) {
  9348. return;
  9349. }
  9350. this._startMonitoringTime = Tools.Now;
  9351. };
  9352. /**
  9353. * Compute the time lapsed since the previous beginMonitoring() call.
  9354. * @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
  9355. */
  9356. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9357. if (newFrame === void 0) { newFrame = true; }
  9358. if (!PerfCounter.Enabled) {
  9359. return;
  9360. }
  9361. if (newFrame) {
  9362. this.fetchNewFrame();
  9363. }
  9364. var currentTime = Tools.Now;
  9365. this._current = currentTime - this._startMonitoringTime;
  9366. if (newFrame) {
  9367. this._fetchResult();
  9368. }
  9369. };
  9370. PerfCounter.prototype._fetchResult = function () {
  9371. this._totalAccumulated += this._current;
  9372. this._lastSecAccumulated += this._current;
  9373. // Min/Max update
  9374. this._min = Math.min(this._min, this._current);
  9375. this._max = Math.max(this._max, this._current);
  9376. this._average = this._totalAccumulated / this._totalValueCount;
  9377. // Reset last sec?
  9378. var now = Tools.Now;
  9379. if ((now - this._lastSecTime) > 1000) {
  9380. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9381. this._lastSecTime = now;
  9382. this._lastSecAccumulated = 0;
  9383. this._lastSecValueCount = 0;
  9384. }
  9385. };
  9386. PerfCounter.Enabled = true;
  9387. return PerfCounter;
  9388. }());
  9389. BABYLON.PerfCounter = PerfCounter;
  9390. /**
  9391. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9392. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9393. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9394. * @param name The name of the class, case should be preserved
  9395. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9396. */
  9397. function className(name, module) {
  9398. return function (target) {
  9399. target["__bjsclassName__"] = name;
  9400. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9401. };
  9402. }
  9403. BABYLON.className = className;
  9404. /**
  9405. * An implementation of a loop for asynchronous functions.
  9406. */
  9407. var AsyncLoop = /** @class */ (function () {
  9408. /**
  9409. * Constroctor.
  9410. * @param iterations the number of iterations.
  9411. * @param _fn the function to run each iteration
  9412. * @param _successCallback the callback that will be called upon succesful execution
  9413. * @param offset starting offset.
  9414. */
  9415. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9416. if (offset === void 0) { offset = 0; }
  9417. this.iterations = iterations;
  9418. this._fn = _fn;
  9419. this._successCallback = _successCallback;
  9420. this.index = offset - 1;
  9421. this._done = false;
  9422. }
  9423. /**
  9424. * Execute the next iteration. Must be called after the last iteration was finished.
  9425. */
  9426. AsyncLoop.prototype.executeNext = function () {
  9427. if (!this._done) {
  9428. if (this.index + 1 < this.iterations) {
  9429. ++this.index;
  9430. this._fn(this);
  9431. }
  9432. else {
  9433. this.breakLoop();
  9434. }
  9435. }
  9436. };
  9437. /**
  9438. * Break the loop and run the success callback.
  9439. */
  9440. AsyncLoop.prototype.breakLoop = function () {
  9441. this._done = true;
  9442. this._successCallback();
  9443. };
  9444. /**
  9445. * Helper function
  9446. */
  9447. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9448. if (offset === void 0) { offset = 0; }
  9449. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9450. loop.executeNext();
  9451. return loop;
  9452. };
  9453. /**
  9454. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9455. * @param iterations total number of iterations
  9456. * @param syncedIterations number of synchronous iterations in each async iteration.
  9457. * @param fn the function to call each iteration.
  9458. * @param callback a success call back that will be called when iterating stops.
  9459. * @param breakFunction a break condition (optional)
  9460. * @param timeout timeout settings for the setTimeout function. default - 0.
  9461. * @constructor
  9462. */
  9463. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9464. if (timeout === void 0) { timeout = 0; }
  9465. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9466. if (breakFunction && breakFunction())
  9467. loop.breakLoop();
  9468. else {
  9469. setTimeout(function () {
  9470. for (var i = 0; i < syncedIterations; ++i) {
  9471. var iteration = (loop.index * syncedIterations) + i;
  9472. if (iteration >= iterations)
  9473. break;
  9474. fn(iteration);
  9475. if (breakFunction && breakFunction()) {
  9476. loop.breakLoop();
  9477. break;
  9478. }
  9479. }
  9480. loop.executeNext();
  9481. }, timeout);
  9482. }
  9483. }, callback);
  9484. };
  9485. return AsyncLoop;
  9486. }());
  9487. BABYLON.AsyncLoop = AsyncLoop;
  9488. })(BABYLON || (BABYLON = {}));
  9489. //# sourceMappingURL=babylon.tools.js.map
  9490. "use strict";
  9491. var BABYLON;
  9492. (function (BABYLON) {
  9493. var PromiseStates;
  9494. (function (PromiseStates) {
  9495. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9496. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9497. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9498. })(PromiseStates || (PromiseStates = {}));
  9499. var FulFillmentAgregator = /** @class */ (function () {
  9500. function FulFillmentAgregator() {
  9501. this.count = 0;
  9502. this.target = 0;
  9503. this.results = [];
  9504. }
  9505. return FulFillmentAgregator;
  9506. }());
  9507. var InternalPromise = /** @class */ (function () {
  9508. function InternalPromise(resolver) {
  9509. var _this = this;
  9510. this._state = PromiseStates.Pending;
  9511. this._children = new Array();
  9512. this._rejectWasConsumed = false;
  9513. if (!resolver) {
  9514. return;
  9515. }
  9516. try {
  9517. resolver(function (value) {
  9518. _this._resolve(value);
  9519. }, function (reason) {
  9520. _this._reject(reason);
  9521. });
  9522. }
  9523. catch (e) {
  9524. this._reject(e);
  9525. }
  9526. }
  9527. InternalPromise.prototype.catch = function (onRejected) {
  9528. return this.then(undefined, onRejected);
  9529. };
  9530. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9531. var _this = this;
  9532. var newPromise = new InternalPromise();
  9533. newPromise._onFulfilled = onFulfilled;
  9534. newPromise._onRejected = onRejected;
  9535. // Composition
  9536. this._children.push(newPromise);
  9537. if (this._state !== PromiseStates.Pending) {
  9538. BABYLON.Tools.SetImmediate(function () {
  9539. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9540. var returnedValue = newPromise._resolve(_this._result);
  9541. if (returnedValue !== undefined && returnedValue !== null) {
  9542. if (returnedValue._state !== undefined) {
  9543. var returnedPromise = returnedValue;
  9544. newPromise._children.push(returnedPromise);
  9545. newPromise = returnedPromise;
  9546. }
  9547. else {
  9548. newPromise._result = returnedValue;
  9549. }
  9550. }
  9551. }
  9552. else {
  9553. newPromise._reject(_this._reason);
  9554. }
  9555. });
  9556. }
  9557. return newPromise;
  9558. };
  9559. InternalPromise.prototype._moveChildren = function (children) {
  9560. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9561. if (this._state === PromiseStates.Fulfilled) {
  9562. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9563. var child = _b[_i];
  9564. child._resolve(this._result);
  9565. }
  9566. }
  9567. else if (this._state === PromiseStates.Rejected) {
  9568. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9569. var child = _d[_c];
  9570. child._reject(this._reason);
  9571. }
  9572. }
  9573. var _a;
  9574. };
  9575. InternalPromise.prototype._resolve = function (value) {
  9576. try {
  9577. this._state = PromiseStates.Fulfilled;
  9578. var returnedValue = null;
  9579. if (this._onFulfilled) {
  9580. returnedValue = this._onFulfilled(value);
  9581. }
  9582. if (returnedValue !== undefined && returnedValue !== null) {
  9583. if (returnedValue._state !== undefined) {
  9584. // Transmit children
  9585. var returnedPromise = returnedValue;
  9586. returnedPromise._moveChildren(this._children);
  9587. value = returnedPromise._result;
  9588. }
  9589. else {
  9590. value = returnedValue;
  9591. }
  9592. }
  9593. this._result = value;
  9594. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9595. var child = _a[_i];
  9596. child._resolve(value);
  9597. }
  9598. this._children.length = 0;
  9599. delete this._onFulfilled;
  9600. delete this._onRejected;
  9601. }
  9602. catch (e) {
  9603. this._reject(e, true);
  9604. }
  9605. };
  9606. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9607. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9608. this._state = PromiseStates.Rejected;
  9609. this._reason = reason;
  9610. if (this._onRejected && !onLocalThrow) {
  9611. try {
  9612. this._onRejected(reason);
  9613. this._rejectWasConsumed = true;
  9614. }
  9615. catch (e) {
  9616. reason = e;
  9617. }
  9618. }
  9619. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9620. var child = _a[_i];
  9621. if (this._rejectWasConsumed) {
  9622. child._resolve(null);
  9623. }
  9624. else {
  9625. child._reject(reason);
  9626. }
  9627. }
  9628. this._children.length = 0;
  9629. delete this._onFulfilled;
  9630. delete this._onRejected;
  9631. };
  9632. InternalPromise.resolve = function (value) {
  9633. var newPromise = new InternalPromise();
  9634. newPromise._resolve(value);
  9635. return newPromise;
  9636. };
  9637. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9638. promise.then(function (value) {
  9639. agregator.results[index] = value;
  9640. agregator.count++;
  9641. if (agregator.count === agregator.target) {
  9642. agregator.rootPromise._resolve(agregator.results);
  9643. }
  9644. return null;
  9645. }, function (reason) {
  9646. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9647. agregator.rootPromise._reject(reason);
  9648. }
  9649. });
  9650. };
  9651. InternalPromise.all = function (promises) {
  9652. var newPromise = new InternalPromise();
  9653. var agregator = new FulFillmentAgregator();
  9654. agregator.target = promises.length;
  9655. agregator.rootPromise = newPromise;
  9656. if (promises.length) {
  9657. for (var index = 0; index < promises.length; index++) {
  9658. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9659. }
  9660. }
  9661. else {
  9662. newPromise._resolve([]);
  9663. }
  9664. return newPromise;
  9665. };
  9666. InternalPromise.race = function (promises) {
  9667. var newPromise = new InternalPromise();
  9668. if (promises.length) {
  9669. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9670. var promise = promises_1[_i];
  9671. promise.then(function (value) {
  9672. if (newPromise) {
  9673. newPromise._resolve(value);
  9674. newPromise = null;
  9675. }
  9676. return null;
  9677. }, function (reason) {
  9678. if (newPromise) {
  9679. newPromise._reject(reason);
  9680. newPromise = null;
  9681. }
  9682. });
  9683. }
  9684. }
  9685. return newPromise;
  9686. };
  9687. return InternalPromise;
  9688. }());
  9689. /**
  9690. * Helper class that provides a small promise polyfill
  9691. */
  9692. var PromisePolyfill = /** @class */ (function () {
  9693. function PromisePolyfill() {
  9694. }
  9695. /**
  9696. * Static function used to check if the polyfill is required
  9697. * If this is the case then the function will inject the polyfill to window.Promise
  9698. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9699. */
  9700. PromisePolyfill.Apply = function (force) {
  9701. if (force === void 0) { force = false; }
  9702. if (force || typeof Promise === 'undefined') {
  9703. var root = window;
  9704. root.Promise = InternalPromise;
  9705. }
  9706. };
  9707. return PromisePolyfill;
  9708. }());
  9709. BABYLON.PromisePolyfill = PromisePolyfill;
  9710. })(BABYLON || (BABYLON = {}));
  9711. //# sourceMappingURL=babylon.promise.js.map
  9712. "use strict";
  9713. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9714. var BABYLON;
  9715. (function (BABYLON) {
  9716. /**
  9717. * Helper class to push actions to a pool of workers.
  9718. */
  9719. var WorkerPool = /** @class */ (function () {
  9720. /**
  9721. * Constructor
  9722. * @param workers Array of workers to use for actions
  9723. */
  9724. function WorkerPool(workers) {
  9725. this._pendingActions = new Array();
  9726. this._workerInfos = workers.map(function (worker) { return ({
  9727. worker: worker,
  9728. active: false
  9729. }); });
  9730. }
  9731. /**
  9732. * Terminates all workers and clears any pending actions.
  9733. */
  9734. WorkerPool.prototype.dispose = function () {
  9735. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9736. var workerInfo = _a[_i];
  9737. workerInfo.worker.terminate();
  9738. }
  9739. delete this._workerInfos;
  9740. delete this._pendingActions;
  9741. };
  9742. /**
  9743. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9744. * pended until a worker has completed its action.
  9745. * @param action The action to perform. Call onComplete when the action is complete.
  9746. */
  9747. WorkerPool.prototype.push = function (action) {
  9748. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9749. var workerInfo = _a[_i];
  9750. if (!workerInfo.active) {
  9751. this._execute(workerInfo, action);
  9752. return;
  9753. }
  9754. }
  9755. this._pendingActions.push(action);
  9756. };
  9757. WorkerPool.prototype._execute = function (workerInfo, action) {
  9758. var _this = this;
  9759. workerInfo.active = true;
  9760. action(workerInfo.worker, function () {
  9761. workerInfo.active = false;
  9762. var nextAction = _this._pendingActions.shift();
  9763. if (nextAction) {
  9764. _this._execute(workerInfo, nextAction);
  9765. }
  9766. });
  9767. };
  9768. return WorkerPool;
  9769. }());
  9770. BABYLON.WorkerPool = WorkerPool;
  9771. })(BABYLON || (BABYLON = {}));
  9772. //# sourceMappingURL=babylon.workerPool.js.map
  9773. "use strict";
  9774. var BABYLON;
  9775. (function (BABYLON) {
  9776. var _AlphaState = /** @class */ (function () {
  9777. /**
  9778. * Initializes the state.
  9779. */
  9780. function _AlphaState() {
  9781. this._isAlphaBlendDirty = false;
  9782. this._isBlendFunctionParametersDirty = false;
  9783. this._isBlendEquationParametersDirty = false;
  9784. this._isBlendConstantsDirty = false;
  9785. this._alphaBlend = false;
  9786. this._blendFunctionParameters = new Array(4);
  9787. this._blendEquationParameters = new Array(2);
  9788. this._blendConstants = new Array(4);
  9789. this.reset();
  9790. }
  9791. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9792. get: function () {
  9793. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9794. },
  9795. enumerable: true,
  9796. configurable: true
  9797. });
  9798. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9799. get: function () {
  9800. return this._alphaBlend;
  9801. },
  9802. set: function (value) {
  9803. if (this._alphaBlend === value) {
  9804. return;
  9805. }
  9806. this._alphaBlend = value;
  9807. this._isAlphaBlendDirty = true;
  9808. },
  9809. enumerable: true,
  9810. configurable: true
  9811. });
  9812. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9813. if (this._blendConstants[0] === r &&
  9814. this._blendConstants[1] === g &&
  9815. this._blendConstants[2] === b &&
  9816. this._blendConstants[3] === a) {
  9817. return;
  9818. }
  9819. this._blendConstants[0] = r;
  9820. this._blendConstants[1] = g;
  9821. this._blendConstants[2] = b;
  9822. this._blendConstants[3] = a;
  9823. this._isBlendConstantsDirty = true;
  9824. };
  9825. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9826. if (this._blendFunctionParameters[0] === value0 &&
  9827. this._blendFunctionParameters[1] === value1 &&
  9828. this._blendFunctionParameters[2] === value2 &&
  9829. this._blendFunctionParameters[3] === value3) {
  9830. return;
  9831. }
  9832. this._blendFunctionParameters[0] = value0;
  9833. this._blendFunctionParameters[1] = value1;
  9834. this._blendFunctionParameters[2] = value2;
  9835. this._blendFunctionParameters[3] = value3;
  9836. this._isBlendFunctionParametersDirty = true;
  9837. };
  9838. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9839. if (this._blendEquationParameters[0] === rgb &&
  9840. this._blendEquationParameters[1] === alpha) {
  9841. return;
  9842. }
  9843. this._blendEquationParameters[0] = rgb;
  9844. this._blendEquationParameters[1] = alpha;
  9845. this._isBlendEquationParametersDirty = true;
  9846. };
  9847. _AlphaState.prototype.reset = function () {
  9848. this._alphaBlend = false;
  9849. this._blendFunctionParameters[0] = null;
  9850. this._blendFunctionParameters[1] = null;
  9851. this._blendFunctionParameters[2] = null;
  9852. this._blendFunctionParameters[3] = null;
  9853. this._blendEquationParameters[0] = null;
  9854. this._blendEquationParameters[1] = null;
  9855. this._blendConstants[0] = null;
  9856. this._blendConstants[1] = null;
  9857. this._blendConstants[2] = null;
  9858. this._blendConstants[3] = null;
  9859. this._isAlphaBlendDirty = true;
  9860. this._isBlendFunctionParametersDirty = false;
  9861. this._isBlendEquationParametersDirty = false;
  9862. this._isBlendConstantsDirty = false;
  9863. };
  9864. _AlphaState.prototype.apply = function (gl) {
  9865. if (!this.isDirty) {
  9866. return;
  9867. }
  9868. // Alpha blend
  9869. if (this._isAlphaBlendDirty) {
  9870. if (this._alphaBlend) {
  9871. gl.enable(gl.BLEND);
  9872. }
  9873. else {
  9874. gl.disable(gl.BLEND);
  9875. }
  9876. this._isAlphaBlendDirty = false;
  9877. }
  9878. // Alpha function
  9879. if (this._isBlendFunctionParametersDirty) {
  9880. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9881. this._isBlendFunctionParametersDirty = false;
  9882. }
  9883. // Alpha equation
  9884. if (this._isBlendEquationParametersDirty) {
  9885. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9886. this._isBlendEquationParametersDirty = false;
  9887. }
  9888. // Constants
  9889. if (this._isBlendConstantsDirty) {
  9890. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9891. this._isBlendConstantsDirty = false;
  9892. }
  9893. };
  9894. return _AlphaState;
  9895. }());
  9896. BABYLON._AlphaState = _AlphaState;
  9897. })(BABYLON || (BABYLON = {}));
  9898. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9899. "use strict";
  9900. var BABYLON;
  9901. (function (BABYLON) {
  9902. var _DepthCullingState = /** @class */ (function () {
  9903. /**
  9904. * Initializes the state.
  9905. */
  9906. function _DepthCullingState() {
  9907. this._isDepthTestDirty = false;
  9908. this._isDepthMaskDirty = false;
  9909. this._isDepthFuncDirty = false;
  9910. this._isCullFaceDirty = false;
  9911. this._isCullDirty = false;
  9912. this._isZOffsetDirty = false;
  9913. this._isFrontFaceDirty = false;
  9914. this.reset();
  9915. }
  9916. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9917. get: function () {
  9918. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9919. },
  9920. enumerable: true,
  9921. configurable: true
  9922. });
  9923. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9924. get: function () {
  9925. return this._zOffset;
  9926. },
  9927. set: function (value) {
  9928. if (this._zOffset === value) {
  9929. return;
  9930. }
  9931. this._zOffset = value;
  9932. this._isZOffsetDirty = true;
  9933. },
  9934. enumerable: true,
  9935. configurable: true
  9936. });
  9937. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9938. get: function () {
  9939. return this._cullFace;
  9940. },
  9941. set: function (value) {
  9942. if (this._cullFace === value) {
  9943. return;
  9944. }
  9945. this._cullFace = value;
  9946. this._isCullFaceDirty = true;
  9947. },
  9948. enumerable: true,
  9949. configurable: true
  9950. });
  9951. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9952. get: function () {
  9953. return this._cull;
  9954. },
  9955. set: function (value) {
  9956. if (this._cull === value) {
  9957. return;
  9958. }
  9959. this._cull = value;
  9960. this._isCullDirty = true;
  9961. },
  9962. enumerable: true,
  9963. configurable: true
  9964. });
  9965. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9966. get: function () {
  9967. return this._depthFunc;
  9968. },
  9969. set: function (value) {
  9970. if (this._depthFunc === value) {
  9971. return;
  9972. }
  9973. this._depthFunc = value;
  9974. this._isDepthFuncDirty = true;
  9975. },
  9976. enumerable: true,
  9977. configurable: true
  9978. });
  9979. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9980. get: function () {
  9981. return this._depthMask;
  9982. },
  9983. set: function (value) {
  9984. if (this._depthMask === value) {
  9985. return;
  9986. }
  9987. this._depthMask = value;
  9988. this._isDepthMaskDirty = true;
  9989. },
  9990. enumerable: true,
  9991. configurable: true
  9992. });
  9993. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9994. get: function () {
  9995. return this._depthTest;
  9996. },
  9997. set: function (value) {
  9998. if (this._depthTest === value) {
  9999. return;
  10000. }
  10001. this._depthTest = value;
  10002. this._isDepthTestDirty = true;
  10003. },
  10004. enumerable: true,
  10005. configurable: true
  10006. });
  10007. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10008. get: function () {
  10009. return this._frontFace;
  10010. },
  10011. set: function (value) {
  10012. if (this._frontFace === value) {
  10013. return;
  10014. }
  10015. this._frontFace = value;
  10016. this._isFrontFaceDirty = true;
  10017. },
  10018. enumerable: true,
  10019. configurable: true
  10020. });
  10021. _DepthCullingState.prototype.reset = function () {
  10022. this._depthMask = true;
  10023. this._depthTest = true;
  10024. this._depthFunc = null;
  10025. this._cullFace = null;
  10026. this._cull = null;
  10027. this._zOffset = 0;
  10028. this._frontFace = null;
  10029. this._isDepthTestDirty = true;
  10030. this._isDepthMaskDirty = true;
  10031. this._isDepthFuncDirty = false;
  10032. this._isCullFaceDirty = false;
  10033. this._isCullDirty = false;
  10034. this._isZOffsetDirty = false;
  10035. this._isFrontFaceDirty = false;
  10036. };
  10037. _DepthCullingState.prototype.apply = function (gl) {
  10038. if (!this.isDirty) {
  10039. return;
  10040. }
  10041. // Cull
  10042. if (this._isCullDirty) {
  10043. if (this.cull) {
  10044. gl.enable(gl.CULL_FACE);
  10045. }
  10046. else {
  10047. gl.disable(gl.CULL_FACE);
  10048. }
  10049. this._isCullDirty = false;
  10050. }
  10051. // Cull face
  10052. if (this._isCullFaceDirty) {
  10053. gl.cullFace(this.cullFace);
  10054. this._isCullFaceDirty = false;
  10055. }
  10056. // Depth mask
  10057. if (this._isDepthMaskDirty) {
  10058. gl.depthMask(this.depthMask);
  10059. this._isDepthMaskDirty = false;
  10060. }
  10061. // Depth test
  10062. if (this._isDepthTestDirty) {
  10063. if (this.depthTest) {
  10064. gl.enable(gl.DEPTH_TEST);
  10065. }
  10066. else {
  10067. gl.disable(gl.DEPTH_TEST);
  10068. }
  10069. this._isDepthTestDirty = false;
  10070. }
  10071. // Depth func
  10072. if (this._isDepthFuncDirty) {
  10073. gl.depthFunc(this.depthFunc);
  10074. this._isDepthFuncDirty = false;
  10075. }
  10076. // zOffset
  10077. if (this._isZOffsetDirty) {
  10078. if (this.zOffset) {
  10079. gl.enable(gl.POLYGON_OFFSET_FILL);
  10080. gl.polygonOffset(this.zOffset, 0);
  10081. }
  10082. else {
  10083. gl.disable(gl.POLYGON_OFFSET_FILL);
  10084. }
  10085. this._isZOffsetDirty = false;
  10086. }
  10087. // Front face
  10088. if (this._isFrontFaceDirty) {
  10089. gl.frontFace(this.frontFace);
  10090. this._isFrontFaceDirty = false;
  10091. }
  10092. };
  10093. return _DepthCullingState;
  10094. }());
  10095. BABYLON._DepthCullingState = _DepthCullingState;
  10096. })(BABYLON || (BABYLON = {}));
  10097. //# sourceMappingURL=babylon.depthCullingState.js.map
  10098. "use strict";
  10099. var BABYLON;
  10100. (function (BABYLON) {
  10101. var _StencilState = /** @class */ (function () {
  10102. function _StencilState() {
  10103. this._isStencilTestDirty = false;
  10104. this._isStencilMaskDirty = false;
  10105. this._isStencilFuncDirty = false;
  10106. this._isStencilOpDirty = false;
  10107. this.reset();
  10108. }
  10109. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10110. get: function () {
  10111. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10112. },
  10113. enumerable: true,
  10114. configurable: true
  10115. });
  10116. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10117. get: function () {
  10118. return this._stencilFunc;
  10119. },
  10120. set: function (value) {
  10121. if (this._stencilFunc === value) {
  10122. return;
  10123. }
  10124. this._stencilFunc = value;
  10125. this._isStencilFuncDirty = true;
  10126. },
  10127. enumerable: true,
  10128. configurable: true
  10129. });
  10130. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10131. get: function () {
  10132. return this._stencilFuncRef;
  10133. },
  10134. set: function (value) {
  10135. if (this._stencilFuncRef === value) {
  10136. return;
  10137. }
  10138. this._stencilFuncRef = value;
  10139. this._isStencilFuncDirty = true;
  10140. },
  10141. enumerable: true,
  10142. configurable: true
  10143. });
  10144. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10145. get: function () {
  10146. return this._stencilFuncMask;
  10147. },
  10148. set: function (value) {
  10149. if (this._stencilFuncMask === value) {
  10150. return;
  10151. }
  10152. this._stencilFuncMask = value;
  10153. this._isStencilFuncDirty = true;
  10154. },
  10155. enumerable: true,
  10156. configurable: true
  10157. });
  10158. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10159. get: function () {
  10160. return this._stencilOpStencilFail;
  10161. },
  10162. set: function (value) {
  10163. if (this._stencilOpStencilFail === value) {
  10164. return;
  10165. }
  10166. this._stencilOpStencilFail = value;
  10167. this._isStencilOpDirty = true;
  10168. },
  10169. enumerable: true,
  10170. configurable: true
  10171. });
  10172. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10173. get: function () {
  10174. return this._stencilOpDepthFail;
  10175. },
  10176. set: function (value) {
  10177. if (this._stencilOpDepthFail === value) {
  10178. return;
  10179. }
  10180. this._stencilOpDepthFail = value;
  10181. this._isStencilOpDirty = true;
  10182. },
  10183. enumerable: true,
  10184. configurable: true
  10185. });
  10186. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10187. get: function () {
  10188. return this._stencilOpStencilDepthPass;
  10189. },
  10190. set: function (value) {
  10191. if (this._stencilOpStencilDepthPass === value) {
  10192. return;
  10193. }
  10194. this._stencilOpStencilDepthPass = value;
  10195. this._isStencilOpDirty = true;
  10196. },
  10197. enumerable: true,
  10198. configurable: true
  10199. });
  10200. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10201. get: function () {
  10202. return this._stencilMask;
  10203. },
  10204. set: function (value) {
  10205. if (this._stencilMask === value) {
  10206. return;
  10207. }
  10208. this._stencilMask = value;
  10209. this._isStencilMaskDirty = true;
  10210. },
  10211. enumerable: true,
  10212. configurable: true
  10213. });
  10214. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10215. get: function () {
  10216. return this._stencilTest;
  10217. },
  10218. set: function (value) {
  10219. if (this._stencilTest === value) {
  10220. return;
  10221. }
  10222. this._stencilTest = value;
  10223. this._isStencilTestDirty = true;
  10224. },
  10225. enumerable: true,
  10226. configurable: true
  10227. });
  10228. _StencilState.prototype.reset = function () {
  10229. this._stencilTest = false;
  10230. this._stencilMask = 0xFF;
  10231. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10232. this._stencilFuncRef = 1;
  10233. this._stencilFuncMask = 0xFF;
  10234. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10235. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10236. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10237. this._isStencilTestDirty = true;
  10238. this._isStencilMaskDirty = true;
  10239. this._isStencilFuncDirty = true;
  10240. this._isStencilOpDirty = true;
  10241. };
  10242. _StencilState.prototype.apply = function (gl) {
  10243. if (!this.isDirty) {
  10244. return;
  10245. }
  10246. // Stencil test
  10247. if (this._isStencilTestDirty) {
  10248. if (this.stencilTest) {
  10249. gl.enable(gl.STENCIL_TEST);
  10250. }
  10251. else {
  10252. gl.disable(gl.STENCIL_TEST);
  10253. }
  10254. this._isStencilTestDirty = false;
  10255. }
  10256. // Stencil mask
  10257. if (this._isStencilMaskDirty) {
  10258. gl.stencilMask(this.stencilMask);
  10259. this._isStencilMaskDirty = false;
  10260. }
  10261. // Stencil func
  10262. if (this._isStencilFuncDirty) {
  10263. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10264. this._isStencilFuncDirty = false;
  10265. }
  10266. // Stencil op
  10267. if (this._isStencilOpDirty) {
  10268. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10269. this._isStencilOpDirty = false;
  10270. }
  10271. };
  10272. return _StencilState;
  10273. }());
  10274. BABYLON._StencilState = _StencilState;
  10275. })(BABYLON || (BABYLON = {}));
  10276. //# sourceMappingURL=babylon.stencilState.js.map
  10277. "use strict";
  10278. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10279. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10280. s = arguments[i];
  10281. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10282. t[p] = s[p];
  10283. }
  10284. return t;
  10285. };
  10286. var BABYLON;
  10287. (function (BABYLON) {
  10288. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10289. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10290. };
  10291. var compileRawShader = function (gl, source, type) {
  10292. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10293. gl.shaderSource(shader, source);
  10294. gl.compileShader(shader);
  10295. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10296. var log = gl.getShaderInfoLog(shader);
  10297. if (log) {
  10298. throw new Error(log);
  10299. }
  10300. }
  10301. if (!shader) {
  10302. throw new Error("Something went wrong while compile the shader.");
  10303. }
  10304. return shader;
  10305. };
  10306. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10307. var magFilter = gl.NEAREST;
  10308. var minFilter = gl.NEAREST;
  10309. switch (samplingMode) {
  10310. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10311. magFilter = gl.LINEAR;
  10312. if (generateMipMaps) {
  10313. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10314. }
  10315. else {
  10316. minFilter = gl.LINEAR;
  10317. }
  10318. break;
  10319. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10320. magFilter = gl.LINEAR;
  10321. if (generateMipMaps) {
  10322. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10323. }
  10324. else {
  10325. minFilter = gl.LINEAR;
  10326. }
  10327. break;
  10328. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10329. magFilter = gl.NEAREST;
  10330. if (generateMipMaps) {
  10331. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10332. }
  10333. else {
  10334. minFilter = gl.NEAREST;
  10335. }
  10336. break;
  10337. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10338. magFilter = gl.NEAREST;
  10339. if (generateMipMaps) {
  10340. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10341. }
  10342. else {
  10343. minFilter = gl.NEAREST;
  10344. }
  10345. break;
  10346. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10347. magFilter = gl.NEAREST;
  10348. if (generateMipMaps) {
  10349. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10350. }
  10351. else {
  10352. minFilter = gl.LINEAR;
  10353. }
  10354. break;
  10355. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10356. magFilter = gl.NEAREST;
  10357. if (generateMipMaps) {
  10358. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10359. }
  10360. else {
  10361. minFilter = gl.LINEAR;
  10362. }
  10363. break;
  10364. case BABYLON.Texture.NEAREST_LINEAR:
  10365. magFilter = gl.NEAREST;
  10366. minFilter = gl.LINEAR;
  10367. break;
  10368. case BABYLON.Texture.NEAREST_NEAREST:
  10369. magFilter = gl.NEAREST;
  10370. minFilter = gl.NEAREST;
  10371. break;
  10372. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10373. magFilter = gl.LINEAR;
  10374. if (generateMipMaps) {
  10375. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10376. }
  10377. else {
  10378. minFilter = gl.NEAREST;
  10379. }
  10380. break;
  10381. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10382. magFilter = gl.LINEAR;
  10383. if (generateMipMaps) {
  10384. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10385. }
  10386. else {
  10387. minFilter = gl.NEAREST;
  10388. }
  10389. break;
  10390. case BABYLON.Texture.LINEAR_LINEAR:
  10391. magFilter = gl.LINEAR;
  10392. minFilter = gl.LINEAR;
  10393. break;
  10394. case BABYLON.Texture.LINEAR_NEAREST:
  10395. magFilter = gl.LINEAR;
  10396. minFilter = gl.NEAREST;
  10397. break;
  10398. }
  10399. return {
  10400. min: minFilter,
  10401. mag: magFilter
  10402. };
  10403. };
  10404. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10405. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10406. var img;
  10407. var onload = function () {
  10408. loadedImages[index] = img;
  10409. loadedImages._internalCount++;
  10410. if (scene) {
  10411. scene._removePendingData(img);
  10412. }
  10413. if (loadedImages._internalCount === 6) {
  10414. onfinish(loadedImages);
  10415. }
  10416. };
  10417. var onerror = function (message, exception) {
  10418. if (scene) {
  10419. scene._removePendingData(img);
  10420. }
  10421. if (onErrorCallBack) {
  10422. onErrorCallBack(message, exception);
  10423. }
  10424. };
  10425. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10426. if (scene) {
  10427. scene._addPendingData(img);
  10428. }
  10429. };
  10430. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10431. if (onError === void 0) { onError = null; }
  10432. var loadedImages = [];
  10433. loadedImages._internalCount = 0;
  10434. for (var index = 0; index < 6; index++) {
  10435. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10436. }
  10437. };
  10438. var BufferPointer = /** @class */ (function () {
  10439. function BufferPointer() {
  10440. }
  10441. return BufferPointer;
  10442. }());
  10443. var InstancingAttributeInfo = /** @class */ (function () {
  10444. function InstancingAttributeInfo() {
  10445. }
  10446. return InstancingAttributeInfo;
  10447. }());
  10448. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10449. /**
  10450. * Define options used to create a render target texture
  10451. */
  10452. var RenderTargetCreationOptions = /** @class */ (function () {
  10453. function RenderTargetCreationOptions() {
  10454. }
  10455. return RenderTargetCreationOptions;
  10456. }());
  10457. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10458. /**
  10459. * Define options used to create a depth texture
  10460. */
  10461. var DepthTextureCreationOptions = /** @class */ (function () {
  10462. function DepthTextureCreationOptions() {
  10463. }
  10464. return DepthTextureCreationOptions;
  10465. }());
  10466. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10467. /**
  10468. * Regroup several parameters relative to the browser in use
  10469. */
  10470. var EngineCapabilities = /** @class */ (function () {
  10471. function EngineCapabilities() {
  10472. }
  10473. return EngineCapabilities;
  10474. }());
  10475. BABYLON.EngineCapabilities = EngineCapabilities;
  10476. /**
  10477. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10478. */
  10479. var Engine = /** @class */ (function () {
  10480. /**
  10481. * @constructor
  10482. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10483. * @param antialias defines enable antialiasing (default: false)
  10484. * @param options defines further options to be sent to the getContext() function
  10485. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10486. */
  10487. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10488. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10489. var _this = this;
  10490. // Public members
  10491. this.forcePOTTextures = false;
  10492. this.isFullscreen = false;
  10493. this.isPointerLock = false;
  10494. this.cullBackFaces = true;
  10495. this.renderEvenInBackground = true;
  10496. this.preventCacheWipeBetweenFrames = false;
  10497. // To enable/disable IDB support and avoid XHR on .manifest
  10498. this.enableOfflineSupport = false;
  10499. this.scenes = new Array();
  10500. this.postProcesses = new Array();
  10501. // Observables
  10502. /**
  10503. * Observable event triggered each time the rendering canvas is resized
  10504. */
  10505. this.onResizeObservable = new BABYLON.Observable();
  10506. /**
  10507. * Observable event triggered each time the canvas loses focus
  10508. */
  10509. this.onCanvasBlurObservable = new BABYLON.Observable();
  10510. /**
  10511. * Observable event triggered each time the canvas gains focus
  10512. */
  10513. this.onCanvasFocusObservable = new BABYLON.Observable();
  10514. /**
  10515. * Observable event triggered each time the canvas receives pointerout event
  10516. */
  10517. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10518. /**
  10519. * Observable event triggered before each texture is initialized
  10520. */
  10521. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10522. //WebVR
  10523. this._vrDisplay = undefined;
  10524. this._vrSupported = false;
  10525. this._vrExclusivePointerMode = false;
  10526. // Uniform buffers list
  10527. this.disableUniformBuffers = false;
  10528. this._uniformBuffers = new Array();
  10529. // Observables
  10530. /**
  10531. * Observable raised when the engine begins a new frame
  10532. */
  10533. this.onBeginFrameObservable = new BABYLON.Observable();
  10534. /**
  10535. * Observable raised when the engine ends the current frame
  10536. */
  10537. this.onEndFrameObservable = new BABYLON.Observable();
  10538. /**
  10539. * Observable raised when the engine is about to compile a shader
  10540. */
  10541. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10542. /**
  10543. * Observable raised when the engine has jsut compiled a shader
  10544. */
  10545. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10546. this._windowIsBackground = false;
  10547. this._webGLVersion = 1.0;
  10548. this._badOS = false;
  10549. this._badDesktopOS = false;
  10550. /**
  10551. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10552. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10553. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10554. */
  10555. this.disableTextureBindingOptimization = false;
  10556. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10557. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10558. this.onVRRequestPresentStart = new BABYLON.Observable();
  10559. this._colorWrite = true;
  10560. this._drawCalls = new BABYLON.PerfCounter();
  10561. this._textureCollisions = new BABYLON.PerfCounter();
  10562. this._renderingQueueLaunched = false;
  10563. this._activeRenderLoops = new Array();
  10564. // Deterministic lockstepMaxSteps
  10565. this._deterministicLockstep = false;
  10566. this._lockstepMaxSteps = 4;
  10567. // Lost context
  10568. this.onContextLostObservable = new BABYLON.Observable();
  10569. this.onContextRestoredObservable = new BABYLON.Observable();
  10570. this._contextWasLost = false;
  10571. this._doNotHandleContextLost = false;
  10572. // FPS
  10573. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10574. this._fps = 60;
  10575. this._deltaTime = 0;
  10576. /**
  10577. * Turn this value on if you want to pause FPS computation when in background
  10578. */
  10579. this.disablePerformanceMonitorInBackground = false;
  10580. // States
  10581. this._depthCullingState = new BABYLON._DepthCullingState();
  10582. this._stencilState = new BABYLON._StencilState();
  10583. this._alphaState = new BABYLON._AlphaState();
  10584. this._alphaMode = Engine.ALPHA_DISABLE;
  10585. // Cache
  10586. this._internalTexturesCache = new Array();
  10587. this._activeChannel = 0;
  10588. this._currentTextureChannel = -1;
  10589. this._boundTexturesCache = {};
  10590. this._compiledEffects = {};
  10591. this._vertexAttribArraysEnabled = [];
  10592. this._uintIndicesCurrentlySet = false;
  10593. this._currentBoundBuffer = new Array();
  10594. this._currentBufferPointers = new Array();
  10595. this._currentInstanceLocations = new Array();
  10596. this._currentInstanceBuffers = new Array();
  10597. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10598. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10599. this._vaoRecordInProgress = false;
  10600. this._mustWipeVertexAttributes = false;
  10601. this._nextFreeTextureSlots = new Array();
  10602. this._maxSimultaneousTextures = 0;
  10603. this._activeRequests = new Array();
  10604. // Hardware supported Compressed Textures
  10605. this._texturesSupported = new Array();
  10606. this._onVRFullScreenTriggered = function () {
  10607. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10608. //get the old size before we change
  10609. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10610. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10611. //get the width and height, change the render size
  10612. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10613. _this.setHardwareScalingLevel(1);
  10614. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10615. }
  10616. else {
  10617. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10618. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10619. }
  10620. };
  10621. this._boundUniforms = {};
  10622. // Register promises
  10623. BABYLON.PromisePolyfill.Apply();
  10624. var canvas = null;
  10625. Engine.Instances.push(this);
  10626. if (!canvasOrContext) {
  10627. return;
  10628. }
  10629. options = options || {};
  10630. if (canvasOrContext.getContext) {
  10631. canvas = canvasOrContext;
  10632. this._renderingCanvas = canvas;
  10633. if (antialias != null) {
  10634. options.antialias = antialias;
  10635. }
  10636. if (options.deterministicLockstep === undefined) {
  10637. options.deterministicLockstep = false;
  10638. }
  10639. if (options.lockstepMaxSteps === undefined) {
  10640. options.lockstepMaxSteps = 4;
  10641. }
  10642. if (options.preserveDrawingBuffer === undefined) {
  10643. options.preserveDrawingBuffer = false;
  10644. }
  10645. if (options.audioEngine === undefined) {
  10646. options.audioEngine = true;
  10647. }
  10648. if (options.stencil === undefined) {
  10649. options.stencil = true;
  10650. }
  10651. this._deterministicLockstep = options.deterministicLockstep;
  10652. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10653. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10654. // Exceptions
  10655. if (navigator && navigator.userAgent) {
  10656. var ua = navigator.userAgent;
  10657. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10658. var exception = _a[_i];
  10659. var key = exception.key;
  10660. var targets = exception.targets;
  10661. if (ua.indexOf(key) > -1) {
  10662. if (exception.capture && exception.captureConstraint) {
  10663. var capture = exception.capture;
  10664. var constraint = exception.captureConstraint;
  10665. var regex = new RegExp(capture);
  10666. var matches = regex.exec(ua);
  10667. if (matches && matches.length > 0) {
  10668. var capturedValue = parseInt(matches[matches.length - 1]);
  10669. if (capturedValue >= constraint) {
  10670. continue;
  10671. }
  10672. }
  10673. }
  10674. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10675. var target = targets_1[_b];
  10676. switch (target) {
  10677. case "uniformBuffer":
  10678. this.disableUniformBuffers = true;
  10679. break;
  10680. case "textureBindingOptimization":
  10681. this.disableTextureBindingOptimization = true;
  10682. break;
  10683. }
  10684. }
  10685. }
  10686. }
  10687. }
  10688. // GL
  10689. if (!options.disableWebGL2Support) {
  10690. try {
  10691. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10692. if (this._gl) {
  10693. this._webGLVersion = 2.0;
  10694. }
  10695. }
  10696. catch (e) {
  10697. // Do nothing
  10698. }
  10699. }
  10700. if (!this._gl) {
  10701. if (!canvas) {
  10702. throw new Error("The provided canvas is null or undefined.");
  10703. }
  10704. try {
  10705. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10706. }
  10707. catch (e) {
  10708. throw new Error("WebGL not supported");
  10709. }
  10710. }
  10711. if (!this._gl) {
  10712. throw new Error("WebGL not supported");
  10713. }
  10714. this._onCanvasFocus = function () {
  10715. _this.onCanvasFocusObservable.notifyObservers(_this);
  10716. };
  10717. this._onCanvasBlur = function () {
  10718. _this.onCanvasBlurObservable.notifyObservers(_this);
  10719. };
  10720. canvas.addEventListener("focus", this._onCanvasFocus);
  10721. canvas.addEventListener("blur", this._onCanvasBlur);
  10722. this._onBlur = function () {
  10723. if (_this.disablePerformanceMonitorInBackground) {
  10724. _this._performanceMonitor.disable();
  10725. }
  10726. _this._windowIsBackground = true;
  10727. };
  10728. this._onFocus = function () {
  10729. if (_this.disablePerformanceMonitorInBackground) {
  10730. _this._performanceMonitor.enable();
  10731. }
  10732. _this._windowIsBackground = false;
  10733. };
  10734. this._onCanvasPointerOut = function (ev) {
  10735. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10736. };
  10737. window.addEventListener("blur", this._onBlur);
  10738. window.addEventListener("focus", this._onFocus);
  10739. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10740. // Context lost
  10741. if (!this._doNotHandleContextLost) {
  10742. this._onContextLost = function (evt) {
  10743. evt.preventDefault();
  10744. _this._contextWasLost = true;
  10745. BABYLON.Tools.Warn("WebGL context lost.");
  10746. _this.onContextLostObservable.notifyObservers(_this);
  10747. };
  10748. this._onContextRestored = function (evt) {
  10749. // Adding a timeout to avoid race condition at browser level
  10750. setTimeout(function () {
  10751. // Rebuild gl context
  10752. _this._initGLContext();
  10753. // Rebuild effects
  10754. _this._rebuildEffects();
  10755. // Rebuild textures
  10756. _this._rebuildInternalTextures();
  10757. // Rebuild buffers
  10758. _this._rebuildBuffers();
  10759. // Cache
  10760. _this.wipeCaches(true);
  10761. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10762. _this.onContextRestoredObservable.notifyObservers(_this);
  10763. _this._contextWasLost = false;
  10764. }, 0);
  10765. };
  10766. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10767. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10768. }
  10769. }
  10770. else {
  10771. this._gl = canvasOrContext;
  10772. this._renderingCanvas = this._gl.canvas;
  10773. if (this._gl.renderbufferStorageMultisample) {
  10774. this._webGLVersion = 2.0;
  10775. }
  10776. options.stencil = this._gl.getContextAttributes().stencil;
  10777. }
  10778. // Viewport
  10779. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10780. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10781. this.resize();
  10782. this._isStencilEnable = options.stencil ? true : false;
  10783. this._initGLContext();
  10784. if (canvas) {
  10785. // Fullscreen
  10786. this._onFullscreenChange = function () {
  10787. if (document.fullscreen !== undefined) {
  10788. _this.isFullscreen = document.fullscreen;
  10789. }
  10790. else if (document.mozFullScreen !== undefined) {
  10791. _this.isFullscreen = document.mozFullScreen;
  10792. }
  10793. else if (document.webkitIsFullScreen !== undefined) {
  10794. _this.isFullscreen = document.webkitIsFullScreen;
  10795. }
  10796. else if (document.msIsFullScreen !== undefined) {
  10797. _this.isFullscreen = document.msIsFullScreen;
  10798. }
  10799. // Pointer lock
  10800. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10801. canvas.requestPointerLock = canvas.requestPointerLock ||
  10802. canvas.msRequestPointerLock ||
  10803. canvas.mozRequestPointerLock ||
  10804. canvas.webkitRequestPointerLock;
  10805. if (canvas.requestPointerLock) {
  10806. canvas.requestPointerLock();
  10807. }
  10808. }
  10809. };
  10810. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10811. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10812. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10813. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10814. // Pointer lock
  10815. this._onPointerLockChange = function () {
  10816. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10817. document.webkitPointerLockElement === canvas ||
  10818. document.msPointerLockElement === canvas ||
  10819. document.pointerLockElement === canvas);
  10820. };
  10821. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10822. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10823. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10824. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10825. this._onVRDisplayPointerRestricted = function () {
  10826. if (canvas) {
  10827. canvas.requestPointerLock();
  10828. }
  10829. };
  10830. this._onVRDisplayPointerUnrestricted = function () {
  10831. document.exitPointerLock();
  10832. };
  10833. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10834. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10835. }
  10836. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10837. Engine.audioEngine = new BABYLON.AudioEngine();
  10838. }
  10839. // Prepare buffer pointers
  10840. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10841. this._currentBufferPointers[i] = new BufferPointer();
  10842. }
  10843. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10844. // Load WebVR Devices
  10845. if (options.autoEnableWebVR) {
  10846. this.initWebVR();
  10847. }
  10848. // Detect if we are running on a faulty buggy OS.
  10849. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10850. // Detect if we are running on a faulty buggy desktop OS.
  10851. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10852. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  10853. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10854. }
  10855. Object.defineProperty(Engine, "LastCreatedEngine", {
  10856. get: function () {
  10857. if (Engine.Instances.length === 0) {
  10858. return null;
  10859. }
  10860. return Engine.Instances[Engine.Instances.length - 1];
  10861. },
  10862. enumerable: true,
  10863. configurable: true
  10864. });
  10865. Object.defineProperty(Engine, "LastCreatedScene", {
  10866. get: function () {
  10867. var lastCreatedEngine = Engine.LastCreatedEngine;
  10868. if (!lastCreatedEngine) {
  10869. return null;
  10870. }
  10871. if (lastCreatedEngine.scenes.length === 0) {
  10872. return null;
  10873. }
  10874. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10875. },
  10876. enumerable: true,
  10877. configurable: true
  10878. });
  10879. /**
  10880. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10881. */
  10882. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10883. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10884. var engine = Engine.Instances[engineIndex];
  10885. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10886. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10887. }
  10888. }
  10889. };
  10890. Object.defineProperty(Engine, "NEVER", {
  10891. get: function () {
  10892. return Engine._NEVER;
  10893. },
  10894. enumerable: true,
  10895. configurable: true
  10896. });
  10897. Object.defineProperty(Engine, "ALWAYS", {
  10898. get: function () {
  10899. return Engine._ALWAYS;
  10900. },
  10901. enumerable: true,
  10902. configurable: true
  10903. });
  10904. Object.defineProperty(Engine, "LESS", {
  10905. get: function () {
  10906. return Engine._LESS;
  10907. },
  10908. enumerable: true,
  10909. configurable: true
  10910. });
  10911. Object.defineProperty(Engine, "EQUAL", {
  10912. get: function () {
  10913. return Engine._EQUAL;
  10914. },
  10915. enumerable: true,
  10916. configurable: true
  10917. });
  10918. Object.defineProperty(Engine, "LEQUAL", {
  10919. get: function () {
  10920. return Engine._LEQUAL;
  10921. },
  10922. enumerable: true,
  10923. configurable: true
  10924. });
  10925. Object.defineProperty(Engine, "GREATER", {
  10926. get: function () {
  10927. return Engine._GREATER;
  10928. },
  10929. enumerable: true,
  10930. configurable: true
  10931. });
  10932. Object.defineProperty(Engine, "GEQUAL", {
  10933. get: function () {
  10934. return Engine._GEQUAL;
  10935. },
  10936. enumerable: true,
  10937. configurable: true
  10938. });
  10939. Object.defineProperty(Engine, "NOTEQUAL", {
  10940. get: function () {
  10941. return Engine._NOTEQUAL;
  10942. },
  10943. enumerable: true,
  10944. configurable: true
  10945. });
  10946. Object.defineProperty(Engine, "KEEP", {
  10947. get: function () {
  10948. return Engine._KEEP;
  10949. },
  10950. enumerable: true,
  10951. configurable: true
  10952. });
  10953. Object.defineProperty(Engine, "REPLACE", {
  10954. get: function () {
  10955. return Engine._REPLACE;
  10956. },
  10957. enumerable: true,
  10958. configurable: true
  10959. });
  10960. Object.defineProperty(Engine, "INCR", {
  10961. get: function () {
  10962. return Engine._INCR;
  10963. },
  10964. enumerable: true,
  10965. configurable: true
  10966. });
  10967. Object.defineProperty(Engine, "DECR", {
  10968. get: function () {
  10969. return Engine._DECR;
  10970. },
  10971. enumerable: true,
  10972. configurable: true
  10973. });
  10974. Object.defineProperty(Engine, "INVERT", {
  10975. get: function () {
  10976. return Engine._INVERT;
  10977. },
  10978. enumerable: true,
  10979. configurable: true
  10980. });
  10981. Object.defineProperty(Engine, "INCR_WRAP", {
  10982. get: function () {
  10983. return Engine._INCR_WRAP;
  10984. },
  10985. enumerable: true,
  10986. configurable: true
  10987. });
  10988. Object.defineProperty(Engine, "DECR_WRAP", {
  10989. get: function () {
  10990. return Engine._DECR_WRAP;
  10991. },
  10992. enumerable: true,
  10993. configurable: true
  10994. });
  10995. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10996. get: function () {
  10997. return Engine._ALPHA_DISABLE;
  10998. },
  10999. enumerable: true,
  11000. configurable: true
  11001. });
  11002. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11003. get: function () {
  11004. return Engine._ALPHA_ONEONE;
  11005. },
  11006. enumerable: true,
  11007. configurable: true
  11008. });
  11009. Object.defineProperty(Engine, "ALPHA_ADD", {
  11010. get: function () {
  11011. return Engine._ALPHA_ADD;
  11012. },
  11013. enumerable: true,
  11014. configurable: true
  11015. });
  11016. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11017. get: function () {
  11018. return Engine._ALPHA_COMBINE;
  11019. },
  11020. enumerable: true,
  11021. configurable: true
  11022. });
  11023. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11024. get: function () {
  11025. return Engine._ALPHA_SUBTRACT;
  11026. },
  11027. enumerable: true,
  11028. configurable: true
  11029. });
  11030. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11031. get: function () {
  11032. return Engine._ALPHA_MULTIPLY;
  11033. },
  11034. enumerable: true,
  11035. configurable: true
  11036. });
  11037. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11038. get: function () {
  11039. return Engine._ALPHA_MAXIMIZED;
  11040. },
  11041. enumerable: true,
  11042. configurable: true
  11043. });
  11044. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11045. get: function () {
  11046. return Engine._ALPHA_PREMULTIPLIED;
  11047. },
  11048. enumerable: true,
  11049. configurable: true
  11050. });
  11051. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11052. get: function () {
  11053. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11054. },
  11055. enumerable: true,
  11056. configurable: true
  11057. });
  11058. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11059. get: function () {
  11060. return Engine._ALPHA_INTERPOLATE;
  11061. },
  11062. enumerable: true,
  11063. configurable: true
  11064. });
  11065. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11066. get: function () {
  11067. return Engine._ALPHA_SCREENMODE;
  11068. },
  11069. enumerable: true,
  11070. configurable: true
  11071. });
  11072. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11073. get: function () {
  11074. return Engine._DELAYLOADSTATE_NONE;
  11075. },
  11076. enumerable: true,
  11077. configurable: true
  11078. });
  11079. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11080. get: function () {
  11081. return Engine._DELAYLOADSTATE_LOADED;
  11082. },
  11083. enumerable: true,
  11084. configurable: true
  11085. });
  11086. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11087. get: function () {
  11088. return Engine._DELAYLOADSTATE_LOADING;
  11089. },
  11090. enumerable: true,
  11091. configurable: true
  11092. });
  11093. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11094. get: function () {
  11095. return Engine._DELAYLOADSTATE_NOTLOADED;
  11096. },
  11097. enumerable: true,
  11098. configurable: true
  11099. });
  11100. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11101. get: function () {
  11102. return Engine._TEXTUREFORMAT_ALPHA;
  11103. },
  11104. enumerable: true,
  11105. configurable: true
  11106. });
  11107. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11108. get: function () {
  11109. return Engine._TEXTUREFORMAT_LUMINANCE;
  11110. },
  11111. enumerable: true,
  11112. configurable: true
  11113. });
  11114. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11115. /**
  11116. * R32F
  11117. */
  11118. get: function () {
  11119. return Engine._TEXTUREFORMAT_R32F;
  11120. },
  11121. enumerable: true,
  11122. configurable: true
  11123. });
  11124. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11125. /**
  11126. * RG32F
  11127. */
  11128. get: function () {
  11129. return Engine._TEXTUREFORMAT_RG32F;
  11130. },
  11131. enumerable: true,
  11132. configurable: true
  11133. });
  11134. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11135. /**
  11136. * RGB32F
  11137. */
  11138. get: function () {
  11139. return Engine._TEXTUREFORMAT_RGB32F;
  11140. },
  11141. enumerable: true,
  11142. configurable: true
  11143. });
  11144. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11145. /**
  11146. * RGBA32F
  11147. */
  11148. get: function () {
  11149. return Engine._TEXTUREFORMAT_RGBA32F;
  11150. },
  11151. enumerable: true,
  11152. configurable: true
  11153. });
  11154. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11155. get: function () {
  11156. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11157. },
  11158. enumerable: true,
  11159. configurable: true
  11160. });
  11161. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11162. get: function () {
  11163. return Engine._TEXTUREFORMAT_RGB;
  11164. },
  11165. enumerable: true,
  11166. configurable: true
  11167. });
  11168. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11169. get: function () {
  11170. return Engine._TEXTUREFORMAT_RGBA;
  11171. },
  11172. enumerable: true,
  11173. configurable: true
  11174. });
  11175. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11176. get: function () {
  11177. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11178. },
  11179. enumerable: true,
  11180. configurable: true
  11181. });
  11182. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11183. get: function () {
  11184. return Engine._TEXTURETYPE_FLOAT;
  11185. },
  11186. enumerable: true,
  11187. configurable: true
  11188. });
  11189. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11190. get: function () {
  11191. return Engine._TEXTURETYPE_HALF_FLOAT;
  11192. },
  11193. enumerable: true,
  11194. configurable: true
  11195. });
  11196. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11197. get: function () {
  11198. return Engine._SCALEMODE_FLOOR;
  11199. },
  11200. enumerable: true,
  11201. configurable: true
  11202. });
  11203. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11204. get: function () {
  11205. return Engine._SCALEMODE_NEAREST;
  11206. },
  11207. enumerable: true,
  11208. configurable: true
  11209. });
  11210. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11211. get: function () {
  11212. return Engine._SCALEMODE_CEILING;
  11213. },
  11214. enumerable: true,
  11215. configurable: true
  11216. });
  11217. Object.defineProperty(Engine, "Version", {
  11218. get: function () {
  11219. return "3.2.0-beta.1";
  11220. },
  11221. enumerable: true,
  11222. configurable: true
  11223. });
  11224. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11225. get: function () {
  11226. return this._vrExclusivePointerMode;
  11227. },
  11228. enumerable: true,
  11229. configurable: true
  11230. });
  11231. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11232. get: function () {
  11233. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11234. },
  11235. enumerable: true,
  11236. configurable: true
  11237. });
  11238. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11239. get: function () {
  11240. return this._webGLVersion < 2 || this.forcePOTTextures;
  11241. },
  11242. enumerable: true,
  11243. configurable: true
  11244. });
  11245. Object.defineProperty(Engine.prototype, "badOS", {
  11246. get: function () {
  11247. return this._badOS;
  11248. },
  11249. enumerable: true,
  11250. configurable: true
  11251. });
  11252. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11253. get: function () {
  11254. return this._badDesktopOS;
  11255. },
  11256. enumerable: true,
  11257. configurable: true
  11258. });
  11259. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11260. get: function () {
  11261. return this._performanceMonitor;
  11262. },
  11263. enumerable: true,
  11264. configurable: true
  11265. });
  11266. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11267. get: function () {
  11268. return this._texturesSupported;
  11269. },
  11270. enumerable: true,
  11271. configurable: true
  11272. });
  11273. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11274. get: function () {
  11275. return this._textureFormatInUse;
  11276. },
  11277. enumerable: true,
  11278. configurable: true
  11279. });
  11280. Object.defineProperty(Engine.prototype, "currentViewport", {
  11281. get: function () {
  11282. return this._cachedViewport;
  11283. },
  11284. enumerable: true,
  11285. configurable: true
  11286. });
  11287. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11288. // Empty texture
  11289. get: function () {
  11290. if (!this._emptyTexture) {
  11291. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11292. }
  11293. return this._emptyTexture;
  11294. },
  11295. enumerable: true,
  11296. configurable: true
  11297. });
  11298. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11299. get: function () {
  11300. if (!this._emptyTexture3D) {
  11301. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11302. }
  11303. return this._emptyTexture3D;
  11304. },
  11305. enumerable: true,
  11306. configurable: true
  11307. });
  11308. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11309. get: function () {
  11310. if (!this._emptyCubeTexture) {
  11311. var faceData = new Uint8Array(4);
  11312. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11313. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11314. }
  11315. return this._emptyCubeTexture;
  11316. },
  11317. enumerable: true,
  11318. configurable: true
  11319. });
  11320. Engine.prototype._rebuildInternalTextures = function () {
  11321. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11322. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11323. var internalTexture = currentState_1[_i];
  11324. internalTexture._rebuild();
  11325. }
  11326. };
  11327. Engine.prototype._rebuildEffects = function () {
  11328. for (var key in this._compiledEffects) {
  11329. var effect = this._compiledEffects[key];
  11330. effect._prepareEffect();
  11331. }
  11332. BABYLON.Effect.ResetCache();
  11333. };
  11334. Engine.prototype._rebuildBuffers = function () {
  11335. // Index / Vertex
  11336. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11337. var scene = _a[_i];
  11338. scene.resetCachedMaterial();
  11339. scene._rebuildGeometries();
  11340. scene._rebuildTextures();
  11341. }
  11342. // Uniforms
  11343. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11344. var uniformBuffer = _c[_b];
  11345. uniformBuffer._rebuild();
  11346. }
  11347. };
  11348. Engine.prototype._initGLContext = function () {
  11349. // Caps
  11350. this._caps = new EngineCapabilities();
  11351. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11352. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11353. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11354. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11355. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11356. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11357. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11358. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11359. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11360. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11361. // Infos
  11362. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11363. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11364. if (rendererInfo != null) {
  11365. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11366. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11367. }
  11368. if (!this._glVendor) {
  11369. this._glVendor = "Unknown vendor";
  11370. }
  11371. if (!this._glRenderer) {
  11372. this._glRenderer = "Unknown renderer";
  11373. }
  11374. // Constants
  11375. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11376. if (this._gl.RGBA16F !== 0x881A) {
  11377. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11378. }
  11379. if (this._gl.RGBA32F !== 0x8814) {
  11380. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11381. }
  11382. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11383. this._gl.DEPTH24_STENCIL8 = 35056;
  11384. }
  11385. // Extensions
  11386. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11387. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11388. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11389. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11390. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11391. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11392. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11393. 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');
  11394. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11395. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11396. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11397. this._caps.highPrecisionShaderSupported = true;
  11398. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11399. if (this._caps.timerQuery) {
  11400. if (this._webGLVersion === 1) {
  11401. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11402. }
  11403. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11404. }
  11405. // Checks if some of the format renders first to allow the use of webgl inspector.
  11406. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11407. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11408. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11409. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11410. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11411. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11412. if (this._webGLVersion > 1) {
  11413. this._gl.HALF_FLOAT_OES = 0x140B;
  11414. }
  11415. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11416. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11417. // Draw buffers
  11418. if (this._webGLVersion > 1) {
  11419. this._caps.drawBuffersExtension = true;
  11420. }
  11421. else {
  11422. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11423. if (drawBuffersExtension !== null) {
  11424. this._caps.drawBuffersExtension = true;
  11425. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11426. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11427. for (var i = 0; i < 16; i++) {
  11428. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11429. }
  11430. }
  11431. else {
  11432. this._caps.drawBuffersExtension = false;
  11433. }
  11434. }
  11435. // Depth Texture
  11436. if (this._webGLVersion > 1) {
  11437. this._caps.depthTextureExtension = true;
  11438. }
  11439. else {
  11440. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11441. if (depthTextureExtension != null) {
  11442. this._caps.depthTextureExtension = true;
  11443. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11444. }
  11445. }
  11446. // Vertex array object
  11447. if (this._webGLVersion > 1) {
  11448. this._caps.vertexArrayObject = true;
  11449. }
  11450. else {
  11451. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11452. if (vertexArrayObjectExtension != null) {
  11453. this._caps.vertexArrayObject = true;
  11454. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11455. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11456. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11457. }
  11458. else {
  11459. this._caps.vertexArrayObject = false;
  11460. }
  11461. }
  11462. // Instances count
  11463. if (this._webGLVersion > 1) {
  11464. this._caps.instancedArrays = true;
  11465. }
  11466. else {
  11467. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11468. if (instanceExtension != null) {
  11469. this._caps.instancedArrays = true;
  11470. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11471. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11472. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11473. }
  11474. else {
  11475. this._caps.instancedArrays = false;
  11476. }
  11477. }
  11478. // Intelligently add supported compressed formats in order to check for.
  11479. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11480. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11481. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11482. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11483. if (this._caps.astc)
  11484. this.texturesSupported.push('-astc.ktx');
  11485. if (this._caps.s3tc)
  11486. this.texturesSupported.push('-dxt.ktx');
  11487. if (this._caps.pvrtc)
  11488. this.texturesSupported.push('-pvrtc.ktx');
  11489. if (this._caps.etc2)
  11490. this.texturesSupported.push('-etc2.ktx');
  11491. if (this._caps.etc1)
  11492. this.texturesSupported.push('-etc1.ktx');
  11493. if (this._gl.getShaderPrecisionFormat) {
  11494. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11495. if (highp) {
  11496. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11497. }
  11498. }
  11499. // Depth buffer
  11500. this.setDepthBuffer(true);
  11501. this.setDepthFunctionToLessOrEqual();
  11502. this.setDepthWrite(true);
  11503. // Texture maps
  11504. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11505. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11506. this._nextFreeTextureSlots.push(slot);
  11507. }
  11508. };
  11509. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11510. get: function () {
  11511. return this._webGLVersion;
  11512. },
  11513. enumerable: true,
  11514. configurable: true
  11515. });
  11516. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11517. /**
  11518. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11519. */
  11520. get: function () {
  11521. return this._isStencilEnable;
  11522. },
  11523. enumerable: true,
  11524. configurable: true
  11525. });
  11526. Engine.prototype._prepareWorkingCanvas = function () {
  11527. if (this._workingCanvas) {
  11528. return;
  11529. }
  11530. this._workingCanvas = document.createElement("canvas");
  11531. var context = this._workingCanvas.getContext("2d");
  11532. if (context) {
  11533. this._workingContext = context;
  11534. }
  11535. };
  11536. Engine.prototype.resetTextureCache = function () {
  11537. for (var key in this._boundTexturesCache) {
  11538. var boundTexture = this._boundTexturesCache[key];
  11539. if (boundTexture) {
  11540. this._removeDesignatedSlot(boundTexture);
  11541. }
  11542. this._boundTexturesCache[key] = null;
  11543. }
  11544. if (!this.disableTextureBindingOptimization) {
  11545. this._nextFreeTextureSlots = [];
  11546. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11547. this._nextFreeTextureSlots.push(slot);
  11548. }
  11549. }
  11550. this._currentTextureChannel = -1;
  11551. };
  11552. Engine.prototype.isDeterministicLockStep = function () {
  11553. return this._deterministicLockstep;
  11554. };
  11555. Engine.prototype.getLockstepMaxSteps = function () {
  11556. return this._lockstepMaxSteps;
  11557. };
  11558. Engine.prototype.getGlInfo = function () {
  11559. return {
  11560. vendor: this._glVendor,
  11561. renderer: this._glRenderer,
  11562. version: this._glVersion
  11563. };
  11564. };
  11565. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11566. if (useScreen === void 0) { useScreen = false; }
  11567. var viewport = camera.viewport;
  11568. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11569. };
  11570. Engine.prototype.getRenderWidth = function (useScreen) {
  11571. if (useScreen === void 0) { useScreen = false; }
  11572. if (!useScreen && this._currentRenderTarget) {
  11573. return this._currentRenderTarget.width;
  11574. }
  11575. return this._gl.drawingBufferWidth;
  11576. };
  11577. Engine.prototype.getRenderHeight = function (useScreen) {
  11578. if (useScreen === void 0) { useScreen = false; }
  11579. if (!useScreen && this._currentRenderTarget) {
  11580. return this._currentRenderTarget.height;
  11581. }
  11582. return this._gl.drawingBufferHeight;
  11583. };
  11584. Engine.prototype.getRenderingCanvas = function () {
  11585. return this._renderingCanvas;
  11586. };
  11587. Engine.prototype.getRenderingCanvasClientRect = function () {
  11588. if (!this._renderingCanvas) {
  11589. return null;
  11590. }
  11591. return this._renderingCanvas.getBoundingClientRect();
  11592. };
  11593. Engine.prototype.setHardwareScalingLevel = function (level) {
  11594. this._hardwareScalingLevel = level;
  11595. this.resize();
  11596. };
  11597. Engine.prototype.getHardwareScalingLevel = function () {
  11598. return this._hardwareScalingLevel;
  11599. };
  11600. Engine.prototype.getLoadedTexturesCache = function () {
  11601. return this._internalTexturesCache;
  11602. };
  11603. Engine.prototype.getCaps = function () {
  11604. return this._caps;
  11605. };
  11606. Object.defineProperty(Engine.prototype, "drawCalls", {
  11607. /** The number of draw calls submitted last frame */
  11608. get: function () {
  11609. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11610. return 0;
  11611. },
  11612. enumerable: true,
  11613. configurable: true
  11614. });
  11615. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11616. get: function () {
  11617. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11618. return null;
  11619. },
  11620. enumerable: true,
  11621. configurable: true
  11622. });
  11623. Engine.prototype.getDepthFunction = function () {
  11624. return this._depthCullingState.depthFunc;
  11625. };
  11626. Engine.prototype.setDepthFunction = function (depthFunc) {
  11627. this._depthCullingState.depthFunc = depthFunc;
  11628. };
  11629. Engine.prototype.setDepthFunctionToGreater = function () {
  11630. this._depthCullingState.depthFunc = this._gl.GREATER;
  11631. };
  11632. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11633. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11634. };
  11635. Engine.prototype.setDepthFunctionToLess = function () {
  11636. this._depthCullingState.depthFunc = this._gl.LESS;
  11637. };
  11638. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11639. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11640. };
  11641. Engine.prototype.getStencilBuffer = function () {
  11642. return this._stencilState.stencilTest;
  11643. };
  11644. Engine.prototype.setStencilBuffer = function (enable) {
  11645. this._stencilState.stencilTest = enable;
  11646. };
  11647. Engine.prototype.getStencilMask = function () {
  11648. return this._stencilState.stencilMask;
  11649. };
  11650. Engine.prototype.setStencilMask = function (mask) {
  11651. this._stencilState.stencilMask = mask;
  11652. };
  11653. Engine.prototype.getStencilFunction = function () {
  11654. return this._stencilState.stencilFunc;
  11655. };
  11656. Engine.prototype.getStencilFunctionReference = function () {
  11657. return this._stencilState.stencilFuncRef;
  11658. };
  11659. Engine.prototype.getStencilFunctionMask = function () {
  11660. return this._stencilState.stencilFuncMask;
  11661. };
  11662. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11663. this._stencilState.stencilFunc = stencilFunc;
  11664. };
  11665. Engine.prototype.setStencilFunctionReference = function (reference) {
  11666. this._stencilState.stencilFuncRef = reference;
  11667. };
  11668. Engine.prototype.setStencilFunctionMask = function (mask) {
  11669. this._stencilState.stencilFuncMask = mask;
  11670. };
  11671. Engine.prototype.getStencilOperationFail = function () {
  11672. return this._stencilState.stencilOpStencilFail;
  11673. };
  11674. Engine.prototype.getStencilOperationDepthFail = function () {
  11675. return this._stencilState.stencilOpDepthFail;
  11676. };
  11677. Engine.prototype.getStencilOperationPass = function () {
  11678. return this._stencilState.stencilOpStencilDepthPass;
  11679. };
  11680. Engine.prototype.setStencilOperationFail = function (operation) {
  11681. this._stencilState.stencilOpStencilFail = operation;
  11682. };
  11683. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11684. this._stencilState.stencilOpDepthFail = operation;
  11685. };
  11686. Engine.prototype.setStencilOperationPass = function (operation) {
  11687. this._stencilState.stencilOpStencilDepthPass = operation;
  11688. };
  11689. Engine.prototype.setDitheringState = function (value) {
  11690. if (value) {
  11691. this._gl.enable(this._gl.DITHER);
  11692. }
  11693. else {
  11694. this._gl.disable(this._gl.DITHER);
  11695. }
  11696. };
  11697. Engine.prototype.setRasterizerState = function (value) {
  11698. if (value) {
  11699. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11700. }
  11701. else {
  11702. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11703. }
  11704. };
  11705. /**
  11706. * stop executing a render loop function and remove it from the execution array
  11707. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11708. */
  11709. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11710. if (!renderFunction) {
  11711. this._activeRenderLoops = [];
  11712. return;
  11713. }
  11714. var index = this._activeRenderLoops.indexOf(renderFunction);
  11715. if (index >= 0) {
  11716. this._activeRenderLoops.splice(index, 1);
  11717. }
  11718. };
  11719. Engine.prototype._renderLoop = function () {
  11720. if (!this._contextWasLost) {
  11721. var shouldRender = true;
  11722. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11723. shouldRender = false;
  11724. }
  11725. if (shouldRender) {
  11726. // Start new frame
  11727. this.beginFrame();
  11728. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11729. var renderFunction = this._activeRenderLoops[index];
  11730. renderFunction();
  11731. }
  11732. // Present
  11733. this.endFrame();
  11734. }
  11735. }
  11736. if (this._activeRenderLoops.length > 0) {
  11737. // Register new frame
  11738. var requester = null;
  11739. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11740. requester = this._vrDisplay;
  11741. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11742. }
  11743. else {
  11744. this._renderingQueueLaunched = false;
  11745. }
  11746. };
  11747. /**
  11748. * Register and execute a render loop. The engine can have more than one render function.
  11749. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11750. * @example
  11751. * engine.runRenderLoop(function () {
  11752. * scene.render()
  11753. * })
  11754. */
  11755. Engine.prototype.runRenderLoop = function (renderFunction) {
  11756. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11757. return;
  11758. }
  11759. this._activeRenderLoops.push(renderFunction);
  11760. if (!this._renderingQueueLaunched) {
  11761. this._renderingQueueLaunched = true;
  11762. this._bindedRenderFunction = this._renderLoop.bind(this);
  11763. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11764. }
  11765. };
  11766. /**
  11767. * Toggle full screen mode.
  11768. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11769. * @param {any} options - an options object to be sent to the requestFullscreen function
  11770. */
  11771. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11772. if (this.isFullscreen) {
  11773. BABYLON.Tools.ExitFullscreen();
  11774. }
  11775. else {
  11776. this._pointerLockRequested = requestPointerLock;
  11777. if (this._renderingCanvas) {
  11778. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11779. }
  11780. }
  11781. };
  11782. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11783. if (stencil === void 0) { stencil = false; }
  11784. this.applyStates();
  11785. var mode = 0;
  11786. if (backBuffer && color) {
  11787. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11788. mode |= this._gl.COLOR_BUFFER_BIT;
  11789. }
  11790. if (depth) {
  11791. this._gl.clearDepth(1.0);
  11792. mode |= this._gl.DEPTH_BUFFER_BIT;
  11793. }
  11794. if (stencil) {
  11795. this._gl.clearStencil(0);
  11796. mode |= this._gl.STENCIL_BUFFER_BIT;
  11797. }
  11798. this._gl.clear(mode);
  11799. };
  11800. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11801. var gl = this._gl;
  11802. // Save state
  11803. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11804. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11805. // Change state
  11806. gl.enable(gl.SCISSOR_TEST);
  11807. gl.scissor(x, y, width, height);
  11808. // Clear
  11809. this.clear(clearColor, true, true, true);
  11810. // Restore state
  11811. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11812. if (curScissor === true) {
  11813. gl.enable(gl.SCISSOR_TEST);
  11814. }
  11815. else {
  11816. gl.disable(gl.SCISSOR_TEST);
  11817. }
  11818. };
  11819. /**
  11820. * Set the WebGL's viewport
  11821. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11822. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11823. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11824. */
  11825. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11826. var width = requiredWidth || this.getRenderWidth();
  11827. var height = requiredHeight || this.getRenderHeight();
  11828. var x = viewport.x || 0;
  11829. var y = viewport.y || 0;
  11830. this._cachedViewport = viewport;
  11831. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11832. };
  11833. /**
  11834. * Directly set the WebGL Viewport
  11835. * The x, y, width & height are directly passed to the WebGL call
  11836. * @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.
  11837. */
  11838. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11839. var currentViewport = this._cachedViewport;
  11840. this._cachedViewport = null;
  11841. this._gl.viewport(x, y, width, height);
  11842. return currentViewport;
  11843. };
  11844. Engine.prototype.beginFrame = function () {
  11845. this.onBeginFrameObservable.notifyObservers(this);
  11846. this._measureFps();
  11847. };
  11848. Engine.prototype.endFrame = function () {
  11849. //force a flush in case we are using a bad OS.
  11850. if (this._badOS) {
  11851. this.flushFramebuffer();
  11852. }
  11853. //submit frame to the vr device, if enabled
  11854. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11855. // TODO: We should only submit the frame if we read frameData successfully.
  11856. this._vrDisplay.submitFrame();
  11857. }
  11858. this.onEndFrameObservable.notifyObservers(this);
  11859. };
  11860. /**
  11861. * resize the view according to the canvas' size.
  11862. * @example
  11863. * window.addEventListener("resize", function () {
  11864. * engine.resize();
  11865. * });
  11866. */
  11867. Engine.prototype.resize = function () {
  11868. // We're not resizing the size of the canvas while in VR mode & presenting
  11869. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11870. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11871. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11872. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11873. }
  11874. };
  11875. /**
  11876. * force a specific size of the canvas
  11877. * @param {number} width - the new canvas' width
  11878. * @param {number} height - the new canvas' height
  11879. */
  11880. Engine.prototype.setSize = function (width, height) {
  11881. if (!this._renderingCanvas) {
  11882. return;
  11883. }
  11884. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11885. return;
  11886. }
  11887. this._renderingCanvas.width = width;
  11888. this._renderingCanvas.height = height;
  11889. for (var index = 0; index < this.scenes.length; index++) {
  11890. var scene = this.scenes[index];
  11891. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11892. var cam = scene.cameras[camIndex];
  11893. cam._currentRenderId = 0;
  11894. }
  11895. }
  11896. if (this.onResizeObservable.hasObservers) {
  11897. this.onResizeObservable.notifyObservers(this);
  11898. }
  11899. };
  11900. // WebVR functions
  11901. Engine.prototype.isVRDevicePresent = function () {
  11902. return !!this._vrDisplay;
  11903. };
  11904. Engine.prototype.getVRDevice = function () {
  11905. return this._vrDisplay;
  11906. };
  11907. /**
  11908. * Initializes a webVR display and starts listening to display change events.
  11909. * The onVRDisplayChangedObservable will be notified upon these changes.
  11910. * @returns The onVRDisplayChangedObservable.
  11911. */
  11912. Engine.prototype.initWebVR = function () {
  11913. this.initWebVRAsync();
  11914. return this.onVRDisplayChangedObservable;
  11915. };
  11916. /**
  11917. * Initializes a webVR display and starts listening to display change events.
  11918. * The onVRDisplayChangedObservable will be notified upon these changes.
  11919. * @returns A promise containing a VRDisplay and if vr is supported.
  11920. */
  11921. Engine.prototype.initWebVRAsync = function () {
  11922. var _this = this;
  11923. var notifyObservers = function () {
  11924. var eventArgs = {
  11925. vrDisplay: _this._vrDisplay,
  11926. vrSupported: _this._vrSupported
  11927. };
  11928. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11929. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11930. };
  11931. if (!this._onVrDisplayConnect) {
  11932. this._onVrDisplayConnect = function (event) {
  11933. _this._vrDisplay = event.display;
  11934. notifyObservers();
  11935. };
  11936. this._onVrDisplayDisconnect = function () {
  11937. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11938. _this._vrDisplay = undefined;
  11939. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11940. notifyObservers();
  11941. };
  11942. this._onVrDisplayPresentChange = function () {
  11943. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11944. };
  11945. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11946. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11947. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11948. }
  11949. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11950. this._webVRInitPromise.then(notifyObservers);
  11951. return this._webVRInitPromise;
  11952. };
  11953. Engine.prototype.enableVR = function () {
  11954. var _this = this;
  11955. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11956. var onResolved = function () {
  11957. _this.onVRRequestPresentComplete.notifyObservers(true);
  11958. _this._onVRFullScreenTriggered();
  11959. };
  11960. var onRejected = function () {
  11961. _this.onVRRequestPresentComplete.notifyObservers(false);
  11962. };
  11963. this.onVRRequestPresentStart.notifyObservers(this);
  11964. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11965. }
  11966. };
  11967. Engine.prototype.disableVR = function () {
  11968. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11969. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11970. }
  11971. };
  11972. Engine.prototype._getVRDisplaysAsync = function () {
  11973. var _this = this;
  11974. return new Promise(function (res, rej) {
  11975. if (navigator.getVRDisplays) {
  11976. navigator.getVRDisplays().then(function (devices) {
  11977. _this._vrSupported = true;
  11978. // note that devices may actually be an empty array. This is fine;
  11979. // we expect this._vrDisplay to be undefined in this case.
  11980. _this._vrDisplay = devices[0];
  11981. res({
  11982. vrDisplay: _this._vrDisplay,
  11983. vrSupported: _this._vrSupported
  11984. });
  11985. });
  11986. }
  11987. else {
  11988. _this._vrDisplay = undefined;
  11989. _this._vrSupported = false;
  11990. res({
  11991. vrDisplay: _this._vrDisplay,
  11992. vrSupported: _this._vrSupported
  11993. });
  11994. }
  11995. });
  11996. };
  11997. /**
  11998. * Binds the frame buffer to the specified texture.
  11999. * @param texture The texture to render to or null for the default canvas
  12000. * @param faceIndex The face of the texture to render to in case of cube texture
  12001. * @param requiredWidth The width of the target to render to
  12002. * @param requiredHeight The height of the target to render to
  12003. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12004. * @param depthStencilTexture The depth stencil texture to use to render
  12005. */
  12006. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12007. if (this._currentRenderTarget) {
  12008. this.unBindFramebuffer(this._currentRenderTarget);
  12009. }
  12010. this._currentRenderTarget = texture;
  12011. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12012. var gl = this._gl;
  12013. if (texture.isCube) {
  12014. if (faceIndex === undefined) {
  12015. faceIndex = 0;
  12016. }
  12017. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12018. if (depthStencilTexture) {
  12019. if (depthStencilTexture._generateStencilBuffer) {
  12020. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12021. }
  12022. else {
  12023. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12024. }
  12025. }
  12026. }
  12027. if (this._cachedViewport && !forceFullscreenViewport) {
  12028. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12029. }
  12030. else {
  12031. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12032. }
  12033. this.wipeCaches();
  12034. };
  12035. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12036. if (this._currentFramebuffer !== framebuffer) {
  12037. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12038. this._currentFramebuffer = framebuffer;
  12039. }
  12040. };
  12041. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12042. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12043. this._currentRenderTarget = null;
  12044. // If MSAA, we need to bitblt back to main texture
  12045. var gl = this._gl;
  12046. if (texture._MSAAFramebuffer) {
  12047. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12048. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12049. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12050. }
  12051. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12052. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12053. gl.generateMipmap(gl.TEXTURE_2D);
  12054. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12055. }
  12056. if (onBeforeUnbind) {
  12057. if (texture._MSAAFramebuffer) {
  12058. // Bind the correct framebuffer
  12059. this.bindUnboundFramebuffer(texture._framebuffer);
  12060. }
  12061. onBeforeUnbind();
  12062. }
  12063. this.bindUnboundFramebuffer(null);
  12064. };
  12065. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12066. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12067. this._currentRenderTarget = null;
  12068. // If MSAA, we need to bitblt back to main texture
  12069. var gl = this._gl;
  12070. if (textures[0]._MSAAFramebuffer) {
  12071. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12072. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12073. var attachments = textures[0]._attachments;
  12074. if (!attachments) {
  12075. attachments = new Array(textures.length);
  12076. textures[0]._attachments = attachments;
  12077. }
  12078. for (var i = 0; i < textures.length; i++) {
  12079. var texture = textures[i];
  12080. for (var j = 0; j < attachments.length; j++) {
  12081. attachments[j] = gl.NONE;
  12082. }
  12083. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12084. gl.readBuffer(attachments[i]);
  12085. gl.drawBuffers(attachments);
  12086. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12087. }
  12088. for (var i = 0; i < attachments.length; i++) {
  12089. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12090. }
  12091. gl.drawBuffers(attachments);
  12092. }
  12093. for (var i = 0; i < textures.length; i++) {
  12094. var texture = textures[i];
  12095. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12096. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12097. gl.generateMipmap(gl.TEXTURE_2D);
  12098. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12099. }
  12100. }
  12101. if (onBeforeUnbind) {
  12102. if (textures[0]._MSAAFramebuffer) {
  12103. // Bind the correct framebuffer
  12104. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12105. }
  12106. onBeforeUnbind();
  12107. }
  12108. this.bindUnboundFramebuffer(null);
  12109. };
  12110. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12111. if (texture.generateMipMaps) {
  12112. var gl = this._gl;
  12113. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12114. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12115. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12116. }
  12117. };
  12118. Engine.prototype.flushFramebuffer = function () {
  12119. this._gl.flush();
  12120. };
  12121. Engine.prototype.restoreDefaultFramebuffer = function () {
  12122. if (this._currentRenderTarget) {
  12123. this.unBindFramebuffer(this._currentRenderTarget);
  12124. }
  12125. else {
  12126. this.bindUnboundFramebuffer(null);
  12127. }
  12128. if (this._cachedViewport) {
  12129. this.setViewport(this._cachedViewport);
  12130. }
  12131. this.wipeCaches();
  12132. };
  12133. // UBOs
  12134. Engine.prototype.createUniformBuffer = function (elements) {
  12135. var ubo = this._gl.createBuffer();
  12136. if (!ubo) {
  12137. throw new Error("Unable to create uniform buffer");
  12138. }
  12139. this.bindUniformBuffer(ubo);
  12140. if (elements instanceof Float32Array) {
  12141. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12142. }
  12143. else {
  12144. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12145. }
  12146. this.bindUniformBuffer(null);
  12147. ubo.references = 1;
  12148. return ubo;
  12149. };
  12150. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12151. var ubo = this._gl.createBuffer();
  12152. if (!ubo) {
  12153. throw new Error("Unable to create dynamic uniform buffer");
  12154. }
  12155. this.bindUniformBuffer(ubo);
  12156. if (elements instanceof Float32Array) {
  12157. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12158. }
  12159. else {
  12160. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12161. }
  12162. this.bindUniformBuffer(null);
  12163. ubo.references = 1;
  12164. return ubo;
  12165. };
  12166. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12167. this.bindUniformBuffer(uniformBuffer);
  12168. if (offset === undefined) {
  12169. offset = 0;
  12170. }
  12171. if (count === undefined) {
  12172. if (elements instanceof Float32Array) {
  12173. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12174. }
  12175. else {
  12176. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12177. }
  12178. }
  12179. else {
  12180. if (elements instanceof Float32Array) {
  12181. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12182. }
  12183. else {
  12184. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12185. }
  12186. }
  12187. this.bindUniformBuffer(null);
  12188. };
  12189. // VBOs
  12190. Engine.prototype._resetVertexBufferBinding = function () {
  12191. this.bindArrayBuffer(null);
  12192. this._cachedVertexBuffers = null;
  12193. };
  12194. Engine.prototype.createVertexBuffer = function (vertices) {
  12195. var vbo = this._gl.createBuffer();
  12196. if (!vbo) {
  12197. throw new Error("Unable to create vertex buffer");
  12198. }
  12199. this.bindArrayBuffer(vbo);
  12200. if (vertices instanceof Float32Array) {
  12201. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  12202. }
  12203. else {
  12204. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  12205. }
  12206. this._resetVertexBufferBinding();
  12207. vbo.references = 1;
  12208. return vbo;
  12209. };
  12210. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12211. var vbo = this._gl.createBuffer();
  12212. if (!vbo) {
  12213. throw new Error("Unable to create dynamic vertex buffer");
  12214. }
  12215. this.bindArrayBuffer(vbo);
  12216. if (vertices instanceof Float32Array) {
  12217. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12218. }
  12219. else {
  12220. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12221. }
  12222. this._resetVertexBufferBinding();
  12223. vbo.references = 1;
  12224. return vbo;
  12225. };
  12226. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12227. if (offset === void 0) { offset = 0; }
  12228. // Force cache update
  12229. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12230. this.bindIndexBuffer(indexBuffer);
  12231. var arrayBuffer;
  12232. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12233. arrayBuffer = indices;
  12234. }
  12235. else {
  12236. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12237. }
  12238. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12239. this._resetIndexBufferBinding();
  12240. };
  12241. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12242. this.bindArrayBuffer(vertexBuffer);
  12243. if (offset === undefined) {
  12244. offset = 0;
  12245. }
  12246. if (count === undefined) {
  12247. if (vertices instanceof Float32Array) {
  12248. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12249. }
  12250. else {
  12251. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12252. }
  12253. }
  12254. else {
  12255. if (vertices instanceof Float32Array) {
  12256. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12257. }
  12258. else {
  12259. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12260. }
  12261. }
  12262. this._resetVertexBufferBinding();
  12263. };
  12264. Engine.prototype._resetIndexBufferBinding = function () {
  12265. this.bindIndexBuffer(null);
  12266. this._cachedIndexBuffer = null;
  12267. };
  12268. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12269. var vbo = this._gl.createBuffer();
  12270. if (!vbo) {
  12271. throw new Error("Unable to create index buffer");
  12272. }
  12273. this.bindIndexBuffer(vbo);
  12274. // Check for 32 bits indices
  12275. var arrayBuffer;
  12276. var need32Bits = false;
  12277. if (indices instanceof Uint16Array) {
  12278. arrayBuffer = indices;
  12279. }
  12280. else {
  12281. //check 32 bit support
  12282. if (this._caps.uintIndices) {
  12283. if (indices instanceof Uint32Array) {
  12284. arrayBuffer = indices;
  12285. need32Bits = true;
  12286. }
  12287. else {
  12288. //number[] or Int32Array, check if 32 bit is necessary
  12289. for (var index = 0; index < indices.length; index++) {
  12290. if (indices[index] > 65535) {
  12291. need32Bits = true;
  12292. break;
  12293. }
  12294. }
  12295. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12296. }
  12297. }
  12298. else {
  12299. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12300. arrayBuffer = new Uint16Array(indices);
  12301. }
  12302. }
  12303. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12304. this._resetIndexBufferBinding();
  12305. vbo.references = 1;
  12306. vbo.is32Bits = need32Bits;
  12307. return vbo;
  12308. };
  12309. Engine.prototype.bindArrayBuffer = function (buffer) {
  12310. if (!this._vaoRecordInProgress) {
  12311. this._unbindVertexArrayObject();
  12312. }
  12313. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12314. };
  12315. Engine.prototype.bindUniformBuffer = function (buffer) {
  12316. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12317. };
  12318. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12319. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12320. };
  12321. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12322. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12323. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12324. };
  12325. ;
  12326. Engine.prototype.bindIndexBuffer = function (buffer) {
  12327. if (!this._vaoRecordInProgress) {
  12328. this._unbindVertexArrayObject();
  12329. }
  12330. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12331. };
  12332. Engine.prototype.bindBuffer = function (buffer, target) {
  12333. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12334. this._gl.bindBuffer(target, buffer);
  12335. this._currentBoundBuffer[target] = buffer;
  12336. }
  12337. };
  12338. Engine.prototype.updateArrayBuffer = function (data) {
  12339. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12340. };
  12341. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12342. var pointer = this._currentBufferPointers[indx];
  12343. var changed = false;
  12344. if (!pointer.active) {
  12345. changed = true;
  12346. pointer.active = true;
  12347. pointer.index = indx;
  12348. pointer.size = size;
  12349. pointer.type = type;
  12350. pointer.normalized = normalized;
  12351. pointer.stride = stride;
  12352. pointer.offset = offset;
  12353. pointer.buffer = buffer;
  12354. }
  12355. else {
  12356. if (pointer.buffer !== buffer) {
  12357. pointer.buffer = buffer;
  12358. changed = true;
  12359. }
  12360. if (pointer.size !== size) {
  12361. pointer.size = size;
  12362. changed = true;
  12363. }
  12364. if (pointer.type !== type) {
  12365. pointer.type = type;
  12366. changed = true;
  12367. }
  12368. if (pointer.normalized !== normalized) {
  12369. pointer.normalized = normalized;
  12370. changed = true;
  12371. }
  12372. if (pointer.stride !== stride) {
  12373. pointer.stride = stride;
  12374. changed = true;
  12375. }
  12376. if (pointer.offset !== offset) {
  12377. pointer.offset = offset;
  12378. changed = true;
  12379. }
  12380. }
  12381. if (changed || this._vaoRecordInProgress) {
  12382. this.bindArrayBuffer(buffer);
  12383. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12384. }
  12385. };
  12386. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12387. if (indexBuffer == null) {
  12388. return;
  12389. }
  12390. if (this._cachedIndexBuffer !== indexBuffer) {
  12391. this._cachedIndexBuffer = indexBuffer;
  12392. this.bindIndexBuffer(indexBuffer);
  12393. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12394. }
  12395. };
  12396. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12397. var attributes = effect.getAttributesNames();
  12398. if (!this._vaoRecordInProgress) {
  12399. this._unbindVertexArrayObject();
  12400. }
  12401. this.unbindAllAttributes();
  12402. for (var index = 0; index < attributes.length; index++) {
  12403. var order = effect.getAttributeLocation(index);
  12404. if (order >= 0) {
  12405. var vertexBuffer = vertexBuffers[attributes[index]];
  12406. if (!vertexBuffer) {
  12407. continue;
  12408. }
  12409. this._gl.enableVertexAttribArray(order);
  12410. if (!this._vaoRecordInProgress) {
  12411. this._vertexAttribArraysEnabled[order] = true;
  12412. }
  12413. var buffer = vertexBuffer.getBuffer();
  12414. if (buffer) {
  12415. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12416. if (vertexBuffer.getIsInstanced()) {
  12417. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12418. if (!this._vaoRecordInProgress) {
  12419. this._currentInstanceLocations.push(order);
  12420. this._currentInstanceBuffers.push(buffer);
  12421. }
  12422. }
  12423. }
  12424. }
  12425. }
  12426. };
  12427. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12428. var vao = this._gl.createVertexArray();
  12429. this._vaoRecordInProgress = true;
  12430. this._gl.bindVertexArray(vao);
  12431. this._mustWipeVertexAttributes = true;
  12432. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12433. this.bindIndexBuffer(indexBuffer);
  12434. this._vaoRecordInProgress = false;
  12435. this._gl.bindVertexArray(null);
  12436. return vao;
  12437. };
  12438. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12439. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12440. this._cachedVertexArrayObject = vertexArrayObject;
  12441. this._gl.bindVertexArray(vertexArrayObject);
  12442. this._cachedVertexBuffers = null;
  12443. this._cachedIndexBuffer = null;
  12444. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12445. this._mustWipeVertexAttributes = true;
  12446. }
  12447. };
  12448. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12449. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12450. this._cachedVertexBuffers = vertexBuffer;
  12451. this._cachedEffectForVertexBuffers = effect;
  12452. var attributesCount = effect.getAttributesCount();
  12453. this._unbindVertexArrayObject();
  12454. this.unbindAllAttributes();
  12455. var offset = 0;
  12456. for (var index = 0; index < attributesCount; index++) {
  12457. if (index < vertexDeclaration.length) {
  12458. var order = effect.getAttributeLocation(index);
  12459. if (order >= 0) {
  12460. this._gl.enableVertexAttribArray(order);
  12461. this._vertexAttribArraysEnabled[order] = true;
  12462. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12463. }
  12464. offset += vertexDeclaration[index] * 4;
  12465. }
  12466. }
  12467. }
  12468. this._bindIndexBufferWithCache(indexBuffer);
  12469. };
  12470. Engine.prototype._unbindVertexArrayObject = function () {
  12471. if (!this._cachedVertexArrayObject) {
  12472. return;
  12473. }
  12474. this._cachedVertexArrayObject = null;
  12475. this._gl.bindVertexArray(null);
  12476. };
  12477. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12478. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12479. this._cachedVertexBuffers = vertexBuffers;
  12480. this._cachedEffectForVertexBuffers = effect;
  12481. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12482. }
  12483. this._bindIndexBufferWithCache(indexBuffer);
  12484. };
  12485. Engine.prototype.unbindInstanceAttributes = function () {
  12486. var boundBuffer;
  12487. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12488. var instancesBuffer = this._currentInstanceBuffers[i];
  12489. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12490. boundBuffer = instancesBuffer;
  12491. this.bindArrayBuffer(instancesBuffer);
  12492. }
  12493. var offsetLocation = this._currentInstanceLocations[i];
  12494. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12495. }
  12496. this._currentInstanceBuffers.length = 0;
  12497. this._currentInstanceLocations.length = 0;
  12498. };
  12499. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12500. this._gl.deleteVertexArray(vao);
  12501. };
  12502. Engine.prototype._releaseBuffer = function (buffer) {
  12503. buffer.references--;
  12504. if (buffer.references === 0) {
  12505. this._gl.deleteBuffer(buffer);
  12506. return true;
  12507. }
  12508. return false;
  12509. };
  12510. Engine.prototype.createInstancesBuffer = function (capacity) {
  12511. var buffer = this._gl.createBuffer();
  12512. if (!buffer) {
  12513. throw new Error("Unable to create instance buffer");
  12514. }
  12515. buffer.capacity = capacity;
  12516. this.bindArrayBuffer(buffer);
  12517. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12518. return buffer;
  12519. };
  12520. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12521. this._gl.deleteBuffer(buffer);
  12522. };
  12523. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12524. this.bindArrayBuffer(instancesBuffer);
  12525. if (data) {
  12526. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12527. }
  12528. if (offsetLocations[0].index !== undefined) {
  12529. var stride = 0;
  12530. for (var i = 0; i < offsetLocations.length; i++) {
  12531. var ai = offsetLocations[i];
  12532. stride += ai.attributeSize * 4;
  12533. }
  12534. for (var i = 0; i < offsetLocations.length; i++) {
  12535. var ai = offsetLocations[i];
  12536. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12537. this._gl.enableVertexAttribArray(ai.index);
  12538. this._vertexAttribArraysEnabled[ai.index] = true;
  12539. }
  12540. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12541. this._gl.vertexAttribDivisor(ai.index, 1);
  12542. this._currentInstanceLocations.push(ai.index);
  12543. this._currentInstanceBuffers.push(instancesBuffer);
  12544. }
  12545. }
  12546. else {
  12547. for (var index = 0; index < 4; index++) {
  12548. var offsetLocation = offsetLocations[index];
  12549. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12550. this._gl.enableVertexAttribArray(offsetLocation);
  12551. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12552. }
  12553. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12554. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12555. this._currentInstanceLocations.push(offsetLocation);
  12556. this._currentInstanceBuffers.push(instancesBuffer);
  12557. }
  12558. }
  12559. };
  12560. Engine.prototype.applyStates = function () {
  12561. this._depthCullingState.apply(this._gl);
  12562. this._stencilState.apply(this._gl);
  12563. this._alphaState.apply(this._gl);
  12564. };
  12565. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12566. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12567. };
  12568. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12569. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12570. };
  12571. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12572. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12573. };
  12574. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12575. // Apply states
  12576. this.applyStates();
  12577. this._drawCalls.addCount(1, false);
  12578. // Render
  12579. var drawMode = this._drawMode(fillMode);
  12580. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12581. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12582. if (instancesCount) {
  12583. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12584. }
  12585. else {
  12586. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12587. }
  12588. };
  12589. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12590. // Apply states
  12591. this.applyStates();
  12592. this._drawCalls.addCount(1, false);
  12593. var drawMode = this._drawMode(fillMode);
  12594. if (instancesCount) {
  12595. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12596. }
  12597. else {
  12598. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12599. }
  12600. };
  12601. Engine.prototype._drawMode = function (fillMode) {
  12602. switch (fillMode) {
  12603. // Triangle views
  12604. case BABYLON.Material.TriangleFillMode:
  12605. return this._gl.TRIANGLES;
  12606. case BABYLON.Material.PointFillMode:
  12607. return this._gl.POINTS;
  12608. case BABYLON.Material.WireFrameFillMode:
  12609. return this._gl.LINES;
  12610. // Draw modes
  12611. case BABYLON.Material.PointListDrawMode:
  12612. return this._gl.POINTS;
  12613. case BABYLON.Material.LineListDrawMode:
  12614. return this._gl.LINES;
  12615. case BABYLON.Material.LineLoopDrawMode:
  12616. return this._gl.LINE_LOOP;
  12617. case BABYLON.Material.LineStripDrawMode:
  12618. return this._gl.LINE_STRIP;
  12619. case BABYLON.Material.TriangleStripDrawMode:
  12620. return this._gl.TRIANGLE_STRIP;
  12621. case BABYLON.Material.TriangleFanDrawMode:
  12622. return this._gl.TRIANGLE_FAN;
  12623. default:
  12624. return this._gl.TRIANGLES;
  12625. }
  12626. };
  12627. // Shaders
  12628. Engine.prototype._releaseEffect = function (effect) {
  12629. if (this._compiledEffects[effect._key]) {
  12630. delete this._compiledEffects[effect._key];
  12631. this._deleteProgram(effect.getProgram());
  12632. }
  12633. };
  12634. Engine.prototype._deleteProgram = function (program) {
  12635. if (program) {
  12636. program.__SPECTOR_rebuildProgram = null;
  12637. if (program.transformFeedback) {
  12638. this.deleteTransformFeedback(program.transformFeedback);
  12639. program.transformFeedback = null;
  12640. }
  12641. this._gl.deleteProgram(program);
  12642. }
  12643. };
  12644. /**
  12645. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12646. * @param samplers An array of string used to represent textures
  12647. */
  12648. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12649. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12650. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12651. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12652. if (this._compiledEffects[name]) {
  12653. var compiledEffect = this._compiledEffects[name];
  12654. if (onCompiled && compiledEffect.isReady()) {
  12655. onCompiled(compiledEffect);
  12656. }
  12657. return compiledEffect;
  12658. }
  12659. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12660. effect._key = name;
  12661. this._compiledEffects[name] = effect;
  12662. return effect;
  12663. };
  12664. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12665. if (uniformsNames === void 0) { uniformsNames = []; }
  12666. if (samplers === void 0) { samplers = []; }
  12667. if (defines === void 0) { defines = ""; }
  12668. return this.createEffect({
  12669. vertex: "particles",
  12670. fragmentElement: fragmentName
  12671. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12672. };
  12673. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12674. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12675. context = context || this._gl;
  12676. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12677. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12678. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12679. };
  12680. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12681. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12682. context = context || this._gl;
  12683. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12684. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  12685. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12686. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12687. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12688. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12689. return program;
  12690. };
  12691. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12692. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12693. var shaderProgram = context.createProgram();
  12694. if (!shaderProgram) {
  12695. throw new Error("Unable to create program");
  12696. }
  12697. context.attachShader(shaderProgram, vertexShader);
  12698. context.attachShader(shaderProgram, fragmentShader);
  12699. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12700. var transformFeedback = this.createTransformFeedback();
  12701. this.bindTransformFeedback(transformFeedback);
  12702. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12703. shaderProgram.transformFeedback = transformFeedback;
  12704. }
  12705. context.linkProgram(shaderProgram);
  12706. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12707. this.bindTransformFeedback(null);
  12708. }
  12709. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12710. if (!linked) {
  12711. context.validateProgram(shaderProgram);
  12712. var error = context.getProgramInfoLog(shaderProgram);
  12713. if (error) {
  12714. throw new Error(error);
  12715. }
  12716. }
  12717. context.deleteShader(vertexShader);
  12718. context.deleteShader(fragmentShader);
  12719. return shaderProgram;
  12720. };
  12721. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12722. var results = new Array();
  12723. for (var index = 0; index < uniformsNames.length; index++) {
  12724. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12725. }
  12726. return results;
  12727. };
  12728. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12729. var results = [];
  12730. for (var index = 0; index < attributesNames.length; index++) {
  12731. try {
  12732. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12733. }
  12734. catch (e) {
  12735. results.push(-1);
  12736. }
  12737. }
  12738. return results;
  12739. };
  12740. Engine.prototype.enableEffect = function (effect) {
  12741. if (!effect) {
  12742. return;
  12743. }
  12744. // Use program
  12745. this.bindSamplers(effect);
  12746. this._currentEffect = effect;
  12747. if (effect.onBind) {
  12748. effect.onBind(effect);
  12749. }
  12750. effect.onBindObservable.notifyObservers(effect);
  12751. };
  12752. Engine.prototype.setIntArray = function (uniform, array) {
  12753. if (!uniform)
  12754. return;
  12755. this._gl.uniform1iv(uniform, array);
  12756. };
  12757. Engine.prototype.setIntArray2 = function (uniform, array) {
  12758. if (!uniform || array.length % 2 !== 0)
  12759. return;
  12760. this._gl.uniform2iv(uniform, array);
  12761. };
  12762. Engine.prototype.setIntArray3 = function (uniform, array) {
  12763. if (!uniform || array.length % 3 !== 0)
  12764. return;
  12765. this._gl.uniform3iv(uniform, array);
  12766. };
  12767. Engine.prototype.setIntArray4 = function (uniform, array) {
  12768. if (!uniform || array.length % 4 !== 0)
  12769. return;
  12770. this._gl.uniform4iv(uniform, array);
  12771. };
  12772. Engine.prototype.setFloatArray = function (uniform, array) {
  12773. if (!uniform)
  12774. return;
  12775. this._gl.uniform1fv(uniform, array);
  12776. };
  12777. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12778. if (!uniform || array.length % 2 !== 0)
  12779. return;
  12780. this._gl.uniform2fv(uniform, array);
  12781. };
  12782. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12783. if (!uniform || array.length % 3 !== 0)
  12784. return;
  12785. this._gl.uniform3fv(uniform, array);
  12786. };
  12787. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12788. if (!uniform || array.length % 4 !== 0)
  12789. return;
  12790. this._gl.uniform4fv(uniform, array);
  12791. };
  12792. Engine.prototype.setArray = function (uniform, array) {
  12793. if (!uniform)
  12794. return;
  12795. this._gl.uniform1fv(uniform, array);
  12796. };
  12797. Engine.prototype.setArray2 = function (uniform, array) {
  12798. if (!uniform || array.length % 2 !== 0)
  12799. return;
  12800. this._gl.uniform2fv(uniform, array);
  12801. };
  12802. Engine.prototype.setArray3 = function (uniform, array) {
  12803. if (!uniform || array.length % 3 !== 0)
  12804. return;
  12805. this._gl.uniform3fv(uniform, array);
  12806. };
  12807. Engine.prototype.setArray4 = function (uniform, array) {
  12808. if (!uniform || array.length % 4 !== 0)
  12809. return;
  12810. this._gl.uniform4fv(uniform, array);
  12811. };
  12812. Engine.prototype.setMatrices = function (uniform, matrices) {
  12813. if (!uniform)
  12814. return;
  12815. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12816. };
  12817. Engine.prototype.setMatrix = function (uniform, matrix) {
  12818. if (!uniform)
  12819. return;
  12820. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12821. };
  12822. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12823. if (!uniform)
  12824. return;
  12825. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12826. };
  12827. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12828. if (!uniform)
  12829. return;
  12830. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12831. };
  12832. Engine.prototype.setInt = function (uniform, value) {
  12833. if (!uniform)
  12834. return;
  12835. this._gl.uniform1i(uniform, value);
  12836. };
  12837. Engine.prototype.setFloat = function (uniform, value) {
  12838. if (!uniform)
  12839. return;
  12840. this._gl.uniform1f(uniform, value);
  12841. };
  12842. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12843. if (!uniform)
  12844. return;
  12845. this._gl.uniform2f(uniform, x, y);
  12846. };
  12847. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12848. if (!uniform)
  12849. return;
  12850. this._gl.uniform3f(uniform, x, y, z);
  12851. };
  12852. Engine.prototype.setBool = function (uniform, bool) {
  12853. if (!uniform)
  12854. return;
  12855. this._gl.uniform1i(uniform, bool);
  12856. };
  12857. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12858. if (!uniform)
  12859. return;
  12860. this._gl.uniform4f(uniform, x, y, z, w);
  12861. };
  12862. Engine.prototype.setColor3 = function (uniform, color3) {
  12863. if (!uniform)
  12864. return;
  12865. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12866. };
  12867. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12868. if (!uniform)
  12869. return;
  12870. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12871. };
  12872. /**
  12873. * Sets a Color4 on a uniform variable
  12874. * @param uniform defines the uniform location
  12875. * @param color4 defines the value to be set
  12876. */
  12877. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12878. if (!uniform)
  12879. return;
  12880. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12881. };
  12882. // States
  12883. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12884. if (zOffset === void 0) { zOffset = 0; }
  12885. if (reverseSide === void 0) { reverseSide = false; }
  12886. // Culling
  12887. if (this._depthCullingState.cull !== culling || force) {
  12888. this._depthCullingState.cull = culling;
  12889. }
  12890. // Cull face
  12891. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12892. if (this._depthCullingState.cullFace !== cullFace || force) {
  12893. this._depthCullingState.cullFace = cullFace;
  12894. }
  12895. // Z offset
  12896. this.setZOffset(zOffset);
  12897. // Front face
  12898. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12899. if (this._depthCullingState.frontFace !== frontFace || force) {
  12900. this._depthCullingState.frontFace = frontFace;
  12901. }
  12902. };
  12903. Engine.prototype.setZOffset = function (value) {
  12904. this._depthCullingState.zOffset = value;
  12905. };
  12906. Engine.prototype.getZOffset = function () {
  12907. return this._depthCullingState.zOffset;
  12908. };
  12909. Engine.prototype.setDepthBuffer = function (enable) {
  12910. this._depthCullingState.depthTest = enable;
  12911. };
  12912. Engine.prototype.getDepthWrite = function () {
  12913. return this._depthCullingState.depthMask;
  12914. };
  12915. Engine.prototype.setDepthWrite = function (enable) {
  12916. this._depthCullingState.depthMask = enable;
  12917. };
  12918. Engine.prototype.setColorWrite = function (enable) {
  12919. this._gl.colorMask(enable, enable, enable, enable);
  12920. this._colorWrite = enable;
  12921. };
  12922. Engine.prototype.getColorWrite = function () {
  12923. return this._colorWrite;
  12924. };
  12925. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12926. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12927. };
  12928. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12929. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12930. if (this._alphaMode === mode) {
  12931. return;
  12932. }
  12933. switch (mode) {
  12934. case Engine.ALPHA_DISABLE:
  12935. this._alphaState.alphaBlend = false;
  12936. break;
  12937. case Engine.ALPHA_PREMULTIPLIED:
  12938. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12939. this._alphaState.alphaBlend = true;
  12940. break;
  12941. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12942. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12943. this._alphaState.alphaBlend = true;
  12944. break;
  12945. case Engine.ALPHA_COMBINE:
  12946. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12947. this._alphaState.alphaBlend = true;
  12948. break;
  12949. case Engine.ALPHA_ONEONE:
  12950. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12951. this._alphaState.alphaBlend = true;
  12952. break;
  12953. case Engine.ALPHA_ADD:
  12954. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12955. this._alphaState.alphaBlend = true;
  12956. break;
  12957. case Engine.ALPHA_SUBTRACT:
  12958. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12959. this._alphaState.alphaBlend = true;
  12960. break;
  12961. case Engine.ALPHA_MULTIPLY:
  12962. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12963. this._alphaState.alphaBlend = true;
  12964. break;
  12965. case Engine.ALPHA_MAXIMIZED:
  12966. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12967. this._alphaState.alphaBlend = true;
  12968. break;
  12969. case Engine.ALPHA_INTERPOLATE:
  12970. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12971. this._alphaState.alphaBlend = true;
  12972. break;
  12973. case Engine.ALPHA_SCREENMODE:
  12974. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12975. this._alphaState.alphaBlend = true;
  12976. break;
  12977. }
  12978. if (!noDepthWriteChange) {
  12979. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12980. }
  12981. this._alphaMode = mode;
  12982. };
  12983. Engine.prototype.getAlphaMode = function () {
  12984. return this._alphaMode;
  12985. };
  12986. // Textures
  12987. Engine.prototype.wipeCaches = function (bruteForce) {
  12988. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12989. return;
  12990. }
  12991. this._currentEffect = null;
  12992. // 6/8/2017: deltakosh: Should not be required anymore.
  12993. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12994. if (bruteForce) {
  12995. this.resetTextureCache();
  12996. this._currentProgram = null;
  12997. this._stencilState.reset();
  12998. this._depthCullingState.reset();
  12999. this.setDepthFunctionToLessOrEqual();
  13000. this._alphaState.reset();
  13001. }
  13002. this._resetVertexBufferBinding();
  13003. this._cachedIndexBuffer = null;
  13004. this._cachedEffectForVertexBuffers = null;
  13005. this._unbindVertexArrayObject();
  13006. this.bindIndexBuffer(null);
  13007. };
  13008. /**
  13009. * Set the compressed texture format to use, based on the formats you have, and the formats
  13010. * supported by the hardware / browser.
  13011. *
  13012. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  13013. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  13014. * to API arguments needed to compressed textures. This puts the burden on the container
  13015. * generator to house the arcane code for determining these for current & future formats.
  13016. *
  13017. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  13018. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  13019. *
  13020. * Note: The result of this call is not taken into account when a texture is base64.
  13021. *
  13022. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  13023. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  13024. *
  13025. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  13026. * @returns The extension selected.
  13027. */
  13028. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  13029. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  13030. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  13031. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  13032. return this._textureFormatInUse = this._texturesSupported[i];
  13033. }
  13034. }
  13035. }
  13036. // actively set format to nothing, to allow this to be called more than once
  13037. // and possibly fail the 2nd time
  13038. this._textureFormatInUse = null;
  13039. return null;
  13040. };
  13041. Engine.prototype._createTexture = function () {
  13042. var texture = this._gl.createTexture();
  13043. if (!texture) {
  13044. throw new Error("Unable to create texture");
  13045. }
  13046. return texture;
  13047. };
  13048. /**
  13049. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  13050. * @param {string} urlArg- This contains one of the following:
  13051. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  13052. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  13053. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  13054. *
  13055. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  13056. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  13057. * @param {Scene} scene- Needed for loading to the correct scene.
  13058. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  13059. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  13060. * @param {callback} onError- Optional callback to be called upon failure.
  13061. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  13062. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  13063. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  13064. *
  13065. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  13066. */
  13067. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  13068. var _this = this;
  13069. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13070. if (onLoad === void 0) { onLoad = null; }
  13071. if (onError === void 0) { onError = null; }
  13072. if (buffer === void 0) { buffer = null; }
  13073. if (fallBack === void 0) { fallBack = null; }
  13074. if (format === void 0) { format = null; }
  13075. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  13076. var fromData = url.substr(0, 5) === "data:";
  13077. var fromBlob = url.substr(0, 5) === "blob:";
  13078. var isBase64 = fromData && url.indexOf("base64") !== -1;
  13079. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  13080. // establish the file extension, if possible
  13081. var lastDot = url.lastIndexOf('.');
  13082. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  13083. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  13084. var isTGA = (extension.indexOf(".tga") === 0);
  13085. // determine if a ktx file should be substituted
  13086. var isKTX = false;
  13087. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  13088. url = url.substring(0, lastDot) + this._textureFormatInUse;
  13089. isKTX = true;
  13090. }
  13091. if (scene) {
  13092. scene._addPendingData(texture);
  13093. }
  13094. texture.url = url;
  13095. texture.generateMipMaps = !noMipmap;
  13096. texture.samplingMode = samplingMode;
  13097. texture.invertY = invertY;
  13098. if (!this._doNotHandleContextLost) {
  13099. // Keep a link to the buffer only if we plan to handle context lost
  13100. texture._buffer = buffer;
  13101. }
  13102. var onLoadObserver = null;
  13103. if (onLoad && !fallBack) {
  13104. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  13105. }
  13106. if (!fallBack)
  13107. this._internalTexturesCache.push(texture);
  13108. var onerror = function (message, exception) {
  13109. if (scene) {
  13110. scene._removePendingData(texture);
  13111. }
  13112. if (onLoadObserver) {
  13113. texture.onLoadedObservable.remove(onLoadObserver);
  13114. }
  13115. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  13116. if (isKTX) {
  13117. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13118. }
  13119. else if (BABYLON.Tools.UseFallbackTexture) {
  13120. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13121. }
  13122. if (onError) {
  13123. onError(message || "Unknown error", exception);
  13124. }
  13125. };
  13126. var callback = null;
  13127. // processing for non-image formats
  13128. if (isKTX || isTGA || isDDS) {
  13129. if (isKTX) {
  13130. callback = function (data) {
  13131. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  13132. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  13133. ktx.uploadLevels(_this._gl, !noMipmap);
  13134. return false;
  13135. }, samplingMode);
  13136. };
  13137. }
  13138. else if (isTGA) {
  13139. callback = function (arrayBuffer) {
  13140. var data = new Uint8Array(arrayBuffer);
  13141. var header = BABYLON.TGATools.GetTGAHeader(data);
  13142. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  13143. BABYLON.TGATools.UploadContent(_this._gl, data);
  13144. return false;
  13145. }, samplingMode);
  13146. };
  13147. }
  13148. else if (isDDS) {
  13149. callback = function (data) {
  13150. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13151. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  13152. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  13153. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  13154. return false;
  13155. }, samplingMode);
  13156. };
  13157. }
  13158. if (!buffer) {
  13159. this._loadFile(url, function (data) {
  13160. if (callback) {
  13161. callback(data);
  13162. }
  13163. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13164. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13165. });
  13166. }
  13167. else {
  13168. if (callback) {
  13169. callback(buffer);
  13170. }
  13171. }
  13172. // image format processing
  13173. }
  13174. else {
  13175. var onload = function (img) {
  13176. if (fromBlob && !_this._doNotHandleContextLost) {
  13177. // We need to store the image if we need to rebuild the texture
  13178. // in case of a webgl context lost
  13179. texture._buffer = img;
  13180. }
  13181. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13182. var gl = _this._gl;
  13183. var isPot = (img.width === potWidth && img.height === potHeight);
  13184. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13185. if (isPot) {
  13186. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13187. return false;
  13188. }
  13189. // Using shaders to rescale because canvas.drawImage is lossy
  13190. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13191. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13192. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13193. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13194. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13195. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13196. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13197. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13198. _this._releaseTexture(source);
  13199. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13200. continuationCallback();
  13201. });
  13202. return true;
  13203. }, samplingMode);
  13204. };
  13205. if (!fromData || isBase64)
  13206. if (buffer instanceof HTMLImageElement) {
  13207. onload(buffer);
  13208. }
  13209. else {
  13210. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13211. }
  13212. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13213. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13214. else
  13215. onload(buffer);
  13216. }
  13217. return texture;
  13218. };
  13219. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13220. var _this = this;
  13221. var rtt = this.createRenderTargetTexture({
  13222. width: destination.width,
  13223. height: destination.height,
  13224. }, {
  13225. generateMipMaps: false,
  13226. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13227. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13228. generateDepthBuffer: false,
  13229. generateStencilBuffer: false
  13230. });
  13231. if (!this._rescalePostProcess) {
  13232. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13233. }
  13234. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13235. _this._rescalePostProcess.onApply = function (effect) {
  13236. effect._bindTexture("textureSampler", source);
  13237. };
  13238. var hostingScene = scene;
  13239. if (!hostingScene) {
  13240. hostingScene = _this.scenes[_this.scenes.length - 1];
  13241. }
  13242. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13243. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13244. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13245. _this.unBindFramebuffer(rtt);
  13246. _this._releaseTexture(rtt);
  13247. if (onComplete) {
  13248. onComplete();
  13249. }
  13250. });
  13251. };
  13252. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13253. if (compression === void 0) { compression = null; }
  13254. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13255. if (!texture) {
  13256. return;
  13257. }
  13258. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13259. var internalFormat = this._getInternalFormat(format);
  13260. var textureType = this._getWebGLTextureType(type);
  13261. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13262. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13263. if (!this._doNotHandleContextLost) {
  13264. texture._bufferView = data;
  13265. texture.format = format;
  13266. texture.type = type;
  13267. texture.invertY = invertY;
  13268. texture._compression = compression;
  13269. }
  13270. if (texture.width % 4 !== 0) {
  13271. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13272. }
  13273. if (compression && data) {
  13274. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13275. }
  13276. else {
  13277. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13278. }
  13279. if (texture.generateMipMaps) {
  13280. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13281. }
  13282. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13283. // this.resetTextureCache();
  13284. texture.isReady = true;
  13285. };
  13286. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13287. if (compression === void 0) { compression = null; }
  13288. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13289. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13290. texture.baseWidth = width;
  13291. texture.baseHeight = height;
  13292. texture.width = width;
  13293. texture.height = height;
  13294. texture.format = format;
  13295. texture.generateMipMaps = generateMipMaps;
  13296. texture.samplingMode = samplingMode;
  13297. texture.invertY = invertY;
  13298. texture._compression = compression;
  13299. texture.type = type;
  13300. if (!this._doNotHandleContextLost) {
  13301. texture._bufferView = data;
  13302. }
  13303. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13304. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13305. // Filters
  13306. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13307. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13308. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13309. if (generateMipMaps) {
  13310. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13311. }
  13312. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13313. this._internalTexturesCache.push(texture);
  13314. return texture;
  13315. };
  13316. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13317. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13318. texture.baseWidth = width;
  13319. texture.baseHeight = height;
  13320. if (generateMipMaps) {
  13321. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13322. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13323. }
  13324. // this.resetTextureCache();
  13325. texture.width = width;
  13326. texture.height = height;
  13327. texture.isReady = false;
  13328. texture.generateMipMaps = generateMipMaps;
  13329. texture.samplingMode = samplingMode;
  13330. this.updateTextureSamplingMode(samplingMode, texture);
  13331. this._internalTexturesCache.push(texture);
  13332. return texture;
  13333. };
  13334. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13335. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13336. if (texture.isCube) {
  13337. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13338. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13339. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13340. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13341. }
  13342. else if (texture.is3D) {
  13343. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13344. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13345. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13346. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13347. }
  13348. else {
  13349. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13350. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13351. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13352. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13353. }
  13354. texture.samplingMode = samplingMode;
  13355. };
  13356. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13357. if (premulAlpha === void 0) { premulAlpha = false; }
  13358. if (!texture) {
  13359. return;
  13360. }
  13361. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13362. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13363. if (premulAlpha) {
  13364. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13365. }
  13366. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13367. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13368. if (texture.generateMipMaps) {
  13369. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13370. }
  13371. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13372. if (premulAlpha) {
  13373. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13374. }
  13375. texture.isReady = true;
  13376. };
  13377. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13378. if (!texture || texture._isDisabled) {
  13379. return;
  13380. }
  13381. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13382. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13383. try {
  13384. // Testing video texture support
  13385. if (this._videoTextureSupported === undefined) {
  13386. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13387. if (this._gl.getError() !== 0) {
  13388. this._videoTextureSupported = false;
  13389. }
  13390. else {
  13391. this._videoTextureSupported = true;
  13392. }
  13393. }
  13394. // Copy video through the current working canvas if video texture is not supported
  13395. if (!this._videoTextureSupported) {
  13396. if (!texture._workingCanvas) {
  13397. texture._workingCanvas = document.createElement("canvas");
  13398. var context = texture._workingCanvas.getContext("2d");
  13399. if (!context) {
  13400. throw new Error("Unable to get 2d context");
  13401. }
  13402. texture._workingContext = context;
  13403. texture._workingCanvas.width = texture.width;
  13404. texture._workingCanvas.height = texture.height;
  13405. }
  13406. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13407. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13408. }
  13409. else {
  13410. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13411. }
  13412. if (texture.generateMipMaps) {
  13413. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13414. }
  13415. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13416. // this.resetTextureCache();
  13417. texture.isReady = true;
  13418. }
  13419. catch (ex) {
  13420. // Something unexpected
  13421. // Let's disable the texture
  13422. texture._isDisabled = true;
  13423. }
  13424. };
  13425. /**
  13426. * Updates a depth texture Comparison Mode and Function.
  13427. * If the comparison Function is equal to 0, the mode will be set to none.
  13428. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13429. * @param texture The texture to set the comparison function for
  13430. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13431. */
  13432. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13433. if (this.webGLVersion === 1) {
  13434. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13435. return;
  13436. }
  13437. var gl = this._gl;
  13438. if (texture.isCube) {
  13439. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13440. if (comparisonFunction === 0) {
  13441. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13442. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13443. }
  13444. else {
  13445. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13446. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13447. }
  13448. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13449. }
  13450. else {
  13451. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13452. if (comparisonFunction === 0) {
  13453. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13454. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13455. }
  13456. else {
  13457. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13458. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13459. }
  13460. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13461. }
  13462. texture._comparisonFunction = comparisonFunction;
  13463. };
  13464. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13465. var width = size.width || size;
  13466. var height = size.height || size;
  13467. internalTexture.baseWidth = width;
  13468. internalTexture.baseHeight = height;
  13469. internalTexture.width = width;
  13470. internalTexture.height = height;
  13471. internalTexture.isReady = true;
  13472. internalTexture.samples = 1;
  13473. internalTexture.generateMipMaps = false;
  13474. internalTexture._generateDepthBuffer = true;
  13475. internalTexture._generateStencilBuffer = generateStencil;
  13476. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13477. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13478. internalTexture._comparisonFunction = comparisonFunction;
  13479. var gl = this._gl;
  13480. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13481. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13482. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13483. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13484. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13485. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13486. if (comparisonFunction === 0) {
  13487. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13488. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13489. }
  13490. else {
  13491. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13492. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13493. }
  13494. };
  13495. /**
  13496. * Creates a depth stencil texture.
  13497. * This is only available in WebGL 2 or with the depth texture extension available.
  13498. * @param size The size of face edge in the texture.
  13499. * @param options The options defining the texture.
  13500. * @returns The texture
  13501. */
  13502. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13503. if (options.isCube) {
  13504. var width = size.width || size;
  13505. return this._createDepthStencilCubeTexture(width, options);
  13506. }
  13507. else {
  13508. return this._createDepthStencilTexture(size, options);
  13509. }
  13510. };
  13511. /**
  13512. * Creates a depth stencil texture.
  13513. * This is only available in WebGL 2 or with the depth texture extension available.
  13514. * @param size The size of face edge in the texture.
  13515. * @param options The options defining the texture.
  13516. * @returns The texture
  13517. */
  13518. Engine.prototype._createDepthStencilTexture = function (size, options) {
  13519. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13520. if (!this._caps.depthTextureExtension) {
  13521. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13522. return internalTexture;
  13523. }
  13524. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13525. var gl = this._gl;
  13526. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13527. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13528. if (this.webGLVersion > 1) {
  13529. if (internalOptions.generateStencil) {
  13530. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13531. }
  13532. else {
  13533. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13534. }
  13535. }
  13536. else {
  13537. if (internalOptions.generateStencil) {
  13538. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13539. }
  13540. else {
  13541. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13542. }
  13543. }
  13544. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13545. return internalTexture;
  13546. };
  13547. /**
  13548. * Creates a depth stencil cube texture.
  13549. * This is only available in WebGL 2.
  13550. * @param size The size of face edge in the cube texture.
  13551. * @param options The options defining the cube texture.
  13552. * @returns The cube texture
  13553. */
  13554. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  13555. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13556. internalTexture.isCube = true;
  13557. if (this.webGLVersion === 1) {
  13558. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13559. return internalTexture;
  13560. }
  13561. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13562. var gl = this._gl;
  13563. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13564. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13565. // Create the depth/stencil buffer
  13566. for (var face = 0; face < 6; face++) {
  13567. if (internalOptions.generateStencil) {
  13568. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13569. }
  13570. else {
  13571. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13572. }
  13573. }
  13574. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13575. return internalTexture;
  13576. };
  13577. /**
  13578. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13579. * @param renderTarget The render target to set the frame buffer for
  13580. */
  13581. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13582. // Create the framebuffer
  13583. var internalTexture = renderTarget.getInternalTexture();
  13584. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13585. return;
  13586. }
  13587. var gl = this._gl;
  13588. var depthStencilTexture = renderTarget.depthStencilTexture;
  13589. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13590. if (depthStencilTexture.isCube) {
  13591. if (depthStencilTexture._generateStencilBuffer) {
  13592. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13593. }
  13594. else {
  13595. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13596. }
  13597. }
  13598. else {
  13599. if (depthStencilTexture._generateStencilBuffer) {
  13600. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13601. }
  13602. else {
  13603. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13604. }
  13605. }
  13606. this.bindUnboundFramebuffer(null);
  13607. };
  13608. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13609. var fullOptions = new RenderTargetCreationOptions();
  13610. if (options !== undefined && typeof options === "object") {
  13611. fullOptions.generateMipMaps = options.generateMipMaps;
  13612. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13613. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13614. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13615. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13616. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  13617. }
  13618. else {
  13619. fullOptions.generateMipMaps = options;
  13620. fullOptions.generateDepthBuffer = true;
  13621. fullOptions.generateStencilBuffer = false;
  13622. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13623. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13624. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  13625. }
  13626. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13627. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13628. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13629. }
  13630. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13631. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13632. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13633. }
  13634. var gl = this._gl;
  13635. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13636. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13637. var width = size.width || size;
  13638. var height = size.height || size;
  13639. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13640. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13641. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13642. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13643. }
  13644. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13645. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13646. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13647. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13648. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  13649. // Create the framebuffer
  13650. var framebuffer = gl.createFramebuffer();
  13651. this.bindUnboundFramebuffer(framebuffer);
  13652. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13653. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13654. if (fullOptions.generateMipMaps) {
  13655. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13656. }
  13657. // Unbind
  13658. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13659. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13660. this.bindUnboundFramebuffer(null);
  13661. texture._framebuffer = framebuffer;
  13662. texture.baseWidth = width;
  13663. texture.baseHeight = height;
  13664. texture.width = width;
  13665. texture.height = height;
  13666. texture.isReady = true;
  13667. texture.samples = 1;
  13668. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13669. texture.samplingMode = fullOptions.samplingMode;
  13670. texture.type = fullOptions.type;
  13671. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13672. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13673. // this.resetTextureCache();
  13674. this._internalTexturesCache.push(texture);
  13675. return texture;
  13676. };
  13677. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13678. var generateMipMaps = false;
  13679. var generateDepthBuffer = true;
  13680. var generateStencilBuffer = false;
  13681. var generateDepthTexture = false;
  13682. var textureCount = 1;
  13683. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13684. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13685. var types = [], samplingModes = [];
  13686. if (options !== undefined) {
  13687. generateMipMaps = options.generateMipMaps;
  13688. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13689. generateStencilBuffer = options.generateStencilBuffer;
  13690. generateDepthTexture = options.generateDepthTexture;
  13691. textureCount = options.textureCount || 1;
  13692. if (options.types) {
  13693. types = options.types;
  13694. }
  13695. if (options.samplingModes) {
  13696. samplingModes = options.samplingModes;
  13697. }
  13698. }
  13699. var gl = this._gl;
  13700. // Create the framebuffer
  13701. var framebuffer = gl.createFramebuffer();
  13702. this.bindUnboundFramebuffer(framebuffer);
  13703. var width = size.width || size;
  13704. var height = size.height || size;
  13705. var textures = [];
  13706. var attachments = [];
  13707. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13708. for (var i = 0; i < textureCount; i++) {
  13709. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13710. var type = types[i] || defaultType;
  13711. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13712. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13713. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13714. }
  13715. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13716. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13717. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13718. }
  13719. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13720. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13721. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13722. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13723. }
  13724. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13725. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13726. textures.push(texture);
  13727. attachments.push(attachment);
  13728. gl.activeTexture(gl["TEXTURE" + i]);
  13729. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13730. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13731. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13732. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13733. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13734. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13735. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13736. if (generateMipMaps) {
  13737. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13738. }
  13739. // Unbind
  13740. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13741. texture._framebuffer = framebuffer;
  13742. texture._depthStencilBuffer = depthStencilBuffer;
  13743. texture.baseWidth = width;
  13744. texture.baseHeight = height;
  13745. texture.width = width;
  13746. texture.height = height;
  13747. texture.isReady = true;
  13748. texture.samples = 1;
  13749. texture.generateMipMaps = generateMipMaps;
  13750. texture.samplingMode = samplingMode;
  13751. texture.type = type;
  13752. texture._generateDepthBuffer = generateDepthBuffer;
  13753. texture._generateStencilBuffer = generateStencilBuffer;
  13754. texture._attachments = attachments;
  13755. this._internalTexturesCache.push(texture);
  13756. }
  13757. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13758. // Depth texture
  13759. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13760. gl.activeTexture(gl.TEXTURE0);
  13761. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13762. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13763. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13764. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13765. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13766. 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);
  13767. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13768. depthTexture._framebuffer = framebuffer;
  13769. depthTexture.baseWidth = width;
  13770. depthTexture.baseHeight = height;
  13771. depthTexture.width = width;
  13772. depthTexture.height = height;
  13773. depthTexture.isReady = true;
  13774. depthTexture.samples = 1;
  13775. depthTexture.generateMipMaps = generateMipMaps;
  13776. depthTexture.samplingMode = gl.NEAREST;
  13777. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13778. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13779. textures.push(depthTexture);
  13780. this._internalTexturesCache.push(depthTexture);
  13781. }
  13782. gl.drawBuffers(attachments);
  13783. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13784. this.bindUnboundFramebuffer(null);
  13785. this.resetTextureCache();
  13786. return textures;
  13787. };
  13788. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13789. if (samples === void 0) { samples = 1; }
  13790. var depthStencilBuffer = null;
  13791. var gl = this._gl;
  13792. // Create the depth/stencil buffer
  13793. if (generateStencilBuffer) {
  13794. depthStencilBuffer = gl.createRenderbuffer();
  13795. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13796. if (samples > 1) {
  13797. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13798. }
  13799. else {
  13800. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13801. }
  13802. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13803. }
  13804. else if (generateDepthBuffer) {
  13805. depthStencilBuffer = gl.createRenderbuffer();
  13806. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13807. if (samples > 1) {
  13808. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13809. }
  13810. else {
  13811. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13812. }
  13813. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13814. }
  13815. return depthStencilBuffer;
  13816. };
  13817. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13818. if (this.webGLVersion < 2 || !texture) {
  13819. return 1;
  13820. }
  13821. if (texture.samples === samples) {
  13822. return samples;
  13823. }
  13824. var gl = this._gl;
  13825. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13826. // Dispose previous render buffers
  13827. if (texture._depthStencilBuffer) {
  13828. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13829. texture._depthStencilBuffer = null;
  13830. }
  13831. if (texture._MSAAFramebuffer) {
  13832. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13833. texture._MSAAFramebuffer = null;
  13834. }
  13835. if (texture._MSAARenderBuffer) {
  13836. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13837. texture._MSAARenderBuffer = null;
  13838. }
  13839. if (samples > 1) {
  13840. var framebuffer = gl.createFramebuffer();
  13841. if (!framebuffer) {
  13842. throw new Error("Unable to create multi sampled framebuffer");
  13843. }
  13844. texture._MSAAFramebuffer = framebuffer;
  13845. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13846. var colorRenderbuffer = gl.createRenderbuffer();
  13847. if (!colorRenderbuffer) {
  13848. throw new Error("Unable to create multi sampled framebuffer");
  13849. }
  13850. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13851. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13852. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13853. texture._MSAARenderBuffer = colorRenderbuffer;
  13854. }
  13855. else {
  13856. this.bindUnboundFramebuffer(texture._framebuffer);
  13857. }
  13858. texture.samples = samples;
  13859. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13860. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13861. this.bindUnboundFramebuffer(null);
  13862. return samples;
  13863. };
  13864. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13865. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13866. return 1;
  13867. }
  13868. if (textures[0].samples === samples) {
  13869. return samples;
  13870. }
  13871. var gl = this._gl;
  13872. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13873. // Dispose previous render buffers
  13874. if (textures[0]._depthStencilBuffer) {
  13875. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13876. textures[0]._depthStencilBuffer = null;
  13877. }
  13878. if (textures[0]._MSAAFramebuffer) {
  13879. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13880. textures[0]._MSAAFramebuffer = null;
  13881. }
  13882. for (var i = 0; i < textures.length; i++) {
  13883. if (textures[i]._MSAARenderBuffer) {
  13884. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13885. textures[i]._MSAARenderBuffer = null;
  13886. }
  13887. }
  13888. if (samples > 1) {
  13889. var framebuffer = gl.createFramebuffer();
  13890. if (!framebuffer) {
  13891. throw new Error("Unable to create multi sampled framebuffer");
  13892. }
  13893. this.bindUnboundFramebuffer(framebuffer);
  13894. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13895. var attachments = [];
  13896. for (var i = 0; i < textures.length; i++) {
  13897. var texture = textures[i];
  13898. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13899. var colorRenderbuffer = gl.createRenderbuffer();
  13900. if (!colorRenderbuffer) {
  13901. throw new Error("Unable to create multi sampled framebuffer");
  13902. }
  13903. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13904. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13905. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13906. texture._MSAAFramebuffer = framebuffer;
  13907. texture._MSAARenderBuffer = colorRenderbuffer;
  13908. texture.samples = samples;
  13909. texture._depthStencilBuffer = depthStencilBuffer;
  13910. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13911. attachments.push(attachment);
  13912. }
  13913. gl.drawBuffers(attachments);
  13914. }
  13915. else {
  13916. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13917. }
  13918. this.bindUnboundFramebuffer(null);
  13919. return samples;
  13920. };
  13921. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13922. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13923. };
  13924. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13925. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13926. };
  13927. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13928. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  13929. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13930. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13931. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13932. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13933. }
  13934. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13935. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13936. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13937. }
  13938. var gl = this._gl;
  13939. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13940. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13941. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13942. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13943. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13944. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13945. }
  13946. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13947. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13948. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13949. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13950. for (var face = 0; face < 6; face++) {
  13951. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  13952. }
  13953. // Create the framebuffer
  13954. var framebuffer = gl.createFramebuffer();
  13955. this.bindUnboundFramebuffer(framebuffer);
  13956. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13957. // MipMaps
  13958. if (fullOptions.generateMipMaps) {
  13959. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13960. }
  13961. // Unbind
  13962. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13963. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13964. this.bindUnboundFramebuffer(null);
  13965. texture._framebuffer = framebuffer;
  13966. texture.width = size;
  13967. texture.height = size;
  13968. texture.isReady = true;
  13969. texture.isCube = true;
  13970. texture.samples = 1;
  13971. texture.generateMipMaps = fullOptions.generateMipMaps;
  13972. texture.samplingMode = fullOptions.samplingMode;
  13973. texture.type = fullOptions.type;
  13974. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13975. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13976. this._internalTexturesCache.push(texture);
  13977. return texture;
  13978. };
  13979. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13980. var _this = this;
  13981. if (onLoad === void 0) { onLoad = null; }
  13982. if (onError === void 0) { onError = null; }
  13983. if (forcedExtension === void 0) { forcedExtension = null; }
  13984. var callback = function (loadData) {
  13985. if (!loadData) {
  13986. if (onLoad) {
  13987. onLoad(null);
  13988. }
  13989. return;
  13990. }
  13991. var texture = loadData.texture;
  13992. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13993. texture._lodGenerationScale = scale;
  13994. texture._lodGenerationOffset = offset;
  13995. if (_this._caps.textureLOD) {
  13996. // Do not add extra process if texture lod is supported.
  13997. if (onLoad) {
  13998. onLoad(texture);
  13999. }
  14000. return;
  14001. }
  14002. var mipSlices = 3;
  14003. var gl = _this._gl;
  14004. var width = loadData.width;
  14005. if (!width) {
  14006. return;
  14007. }
  14008. var textures = [];
  14009. for (var i = 0; i < mipSlices; i++) {
  14010. //compute LOD from even spacing in smoothness (matching shader calculation)
  14011. var smoothness = i / (mipSlices - 1);
  14012. var roughness = 1 - smoothness;
  14013. var minLODIndex = offset; // roughness = 0
  14014. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  14015. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  14016. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  14017. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14018. glTextureFromLod.isCube = true;
  14019. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  14020. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14021. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14022. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14023. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14024. if (loadData.isDDS) {
  14025. var info = loadData.info;
  14026. var data = loadData.data;
  14027. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14028. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  14029. }
  14030. else {
  14031. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  14032. }
  14033. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14034. // Wrap in a base texture for easy binding.
  14035. var lodTexture = new BABYLON.BaseTexture(scene);
  14036. lodTexture.isCube = true;
  14037. lodTexture._texture = glTextureFromLod;
  14038. glTextureFromLod.isReady = true;
  14039. textures.push(lodTexture);
  14040. }
  14041. texture._lodTextureHigh = textures[2];
  14042. texture._lodTextureMid = textures[1];
  14043. texture._lodTextureLow = textures[0];
  14044. if (onLoad) {
  14045. onLoad(texture);
  14046. }
  14047. };
  14048. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  14049. };
  14050. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  14051. var _this = this;
  14052. if (onLoad === void 0) { onLoad = null; }
  14053. if (onError === void 0) { onError = null; }
  14054. if (forcedExtension === void 0) { forcedExtension = null; }
  14055. var gl = this._gl;
  14056. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  14057. texture.isCube = true;
  14058. texture.url = rootUrl;
  14059. texture.generateMipMaps = !noMipmap;
  14060. if (!this._doNotHandleContextLost) {
  14061. texture._extension = forcedExtension;
  14062. texture._files = files;
  14063. }
  14064. var isKTX = false;
  14065. var isDDS = false;
  14066. var lastDot = rootUrl.lastIndexOf('.');
  14067. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  14068. if (this._textureFormatInUse) {
  14069. extension = this._textureFormatInUse;
  14070. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  14071. isKTX = true;
  14072. }
  14073. else {
  14074. isDDS = (extension === ".dds");
  14075. }
  14076. var onerror = function (request, exception) {
  14077. if (onError && request) {
  14078. onError(request.status + " " + request.statusText, exception);
  14079. }
  14080. };
  14081. if (isKTX) {
  14082. this._loadFile(rootUrl, function (data) {
  14083. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  14084. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  14085. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14086. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  14087. ktx.uploadLevels(_this._gl, !noMipmap);
  14088. _this.setCubeMapTextureParams(gl, loadMipmap);
  14089. texture.width = ktx.pixelWidth;
  14090. texture.height = ktx.pixelHeight;
  14091. texture.isReady = true;
  14092. }, undefined, undefined, true, onerror);
  14093. }
  14094. else if (isDDS) {
  14095. if (files && files.length === 6) {
  14096. this._cascadeLoadFiles(scene, function (imgs) {
  14097. var info;
  14098. var loadMipmap = false;
  14099. var width = 0;
  14100. for (var index = 0; index < imgs.length; index++) {
  14101. var data = imgs[index];
  14102. info = BABYLON.DDSTools.GetDDSInfo(data);
  14103. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14104. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14105. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14106. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  14107. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14108. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14109. }
  14110. texture.width = info.width;
  14111. texture.height = info.height;
  14112. texture.type = info.textureType;
  14113. width = info.width;
  14114. }
  14115. _this.setCubeMapTextureParams(gl, loadMipmap);
  14116. texture.isReady = true;
  14117. if (onLoad) {
  14118. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  14119. }
  14120. }, files, onError);
  14121. }
  14122. else {
  14123. this._loadFile(rootUrl, function (data) {
  14124. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14125. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14126. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14127. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14128. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  14129. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14130. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14131. }
  14132. _this.setCubeMapTextureParams(gl, loadMipmap);
  14133. texture.width = info.width;
  14134. texture.height = info.height;
  14135. texture.isReady = true;
  14136. texture.type = info.textureType;
  14137. if (onLoad) {
  14138. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  14139. }
  14140. }, undefined, undefined, true, onerror);
  14141. }
  14142. }
  14143. else {
  14144. if (!files) {
  14145. throw new Error("Cannot load cubemap because files were not defined");
  14146. }
  14147. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  14148. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  14149. var height = width;
  14150. _this._prepareWorkingCanvas();
  14151. if (!_this._workingCanvas || !_this._workingContext) {
  14152. return;
  14153. }
  14154. _this._workingCanvas.width = width;
  14155. _this._workingCanvas.height = height;
  14156. var faces = [
  14157. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  14158. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  14159. ];
  14160. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14161. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14162. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  14163. for (var index = 0; index < faces.length; index++) {
  14164. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  14165. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14166. }
  14167. if (!noMipmap) {
  14168. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14169. }
  14170. _this.setCubeMapTextureParams(gl, !noMipmap);
  14171. texture.width = width;
  14172. texture.height = height;
  14173. texture.isReady = true;
  14174. if (format) {
  14175. texture.format = format;
  14176. }
  14177. texture.onLoadedObservable.notifyObservers(texture);
  14178. texture.onLoadedObservable.clear();
  14179. if (onLoad) {
  14180. onLoad();
  14181. }
  14182. }, files, onError);
  14183. }
  14184. this._internalTexturesCache.push(texture);
  14185. return texture;
  14186. };
  14187. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  14188. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14189. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  14190. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14191. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14192. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14193. // this.resetTextureCache();
  14194. };
  14195. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  14196. if (compression === void 0) { compression = null; }
  14197. if (level === void 0) { level = 0; }
  14198. texture._bufferViewArray = data;
  14199. texture.format = format;
  14200. texture.type = type;
  14201. texture.invertY = invertY;
  14202. texture._compression = compression;
  14203. var gl = this._gl;
  14204. var textureType = this._getWebGLTextureType(type);
  14205. var internalFormat = this._getInternalFormat(format);
  14206. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14207. var needConversion = false;
  14208. if (internalFormat === gl.RGB) {
  14209. internalFormat = gl.RGBA;
  14210. needConversion = true;
  14211. }
  14212. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14213. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14214. if (texture.width % 4 !== 0) {
  14215. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14216. }
  14217. // Data are known to be in +X +Y +Z -X -Y -Z
  14218. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14219. var faceData = data[faceIndex];
  14220. if (compression) {
  14221. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14222. }
  14223. else {
  14224. if (needConversion) {
  14225. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14226. }
  14227. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14228. }
  14229. }
  14230. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14231. if (isPot && texture.generateMipMaps && level === 0) {
  14232. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14233. }
  14234. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14235. // this.resetTextureCache();
  14236. texture.isReady = true;
  14237. };
  14238. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14239. if (compression === void 0) { compression = null; }
  14240. var gl = this._gl;
  14241. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14242. texture.isCube = true;
  14243. texture.generateMipMaps = generateMipMaps;
  14244. texture.format = format;
  14245. texture.type = type;
  14246. if (!this._doNotHandleContextLost) {
  14247. texture._bufferViewArray = data;
  14248. }
  14249. var textureType = this._getWebGLTextureType(type);
  14250. var internalFormat = this._getInternalFormat(format);
  14251. if (internalFormat === gl.RGB) {
  14252. internalFormat = gl.RGBA;
  14253. }
  14254. var width = size;
  14255. var height = width;
  14256. texture.width = width;
  14257. texture.height = height;
  14258. // Double check on POT to generate Mips.
  14259. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14260. if (!isPot) {
  14261. generateMipMaps = false;
  14262. }
  14263. // Upload data if needed. The texture won't be ready until then.
  14264. if (data) {
  14265. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14266. }
  14267. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14268. // Filters
  14269. if (data && generateMipMaps) {
  14270. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14271. }
  14272. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14273. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14274. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14275. }
  14276. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14277. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14278. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14279. }
  14280. else {
  14281. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14282. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14283. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14284. }
  14285. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14286. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14287. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14288. return texture;
  14289. };
  14290. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14291. var _this = this;
  14292. if (onLoad === void 0) { onLoad = null; }
  14293. if (onError === void 0) { onError = null; }
  14294. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14295. if (invertY === void 0) { invertY = false; }
  14296. var gl = this._gl;
  14297. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14298. scene._addPendingData(texture);
  14299. texture.url = url;
  14300. this._internalTexturesCache.push(texture);
  14301. var onerror = function (request, exception) {
  14302. scene._removePendingData(texture);
  14303. if (onError && request) {
  14304. onError(request.status + " " + request.statusText, exception);
  14305. }
  14306. };
  14307. var internalCallback = function (data) {
  14308. var width = texture.width;
  14309. var faceDataArrays = callback(data);
  14310. if (!faceDataArrays) {
  14311. return;
  14312. }
  14313. if (mipmmapGenerator) {
  14314. var textureType = _this._getWebGLTextureType(type);
  14315. var internalFormat = _this._getInternalFormat(format);
  14316. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14317. var needConversion = false;
  14318. if (internalFormat === gl.RGB) {
  14319. internalFormat = gl.RGBA;
  14320. needConversion = true;
  14321. }
  14322. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14323. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14324. var mipData = mipmmapGenerator(faceDataArrays);
  14325. for (var level = 0; level < mipData.length; level++) {
  14326. var mipSize = width >> level;
  14327. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14328. var mipFaceData = mipData[level][faceIndex];
  14329. if (needConversion) {
  14330. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14331. }
  14332. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14333. }
  14334. }
  14335. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14336. }
  14337. else {
  14338. texture.generateMipMaps = !noMipmap;
  14339. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14340. }
  14341. texture.isReady = true;
  14342. // this.resetTextureCache();
  14343. scene._removePendingData(texture);
  14344. if (onLoad) {
  14345. onLoad();
  14346. }
  14347. };
  14348. this._loadFile(url, function (data) {
  14349. internalCallback(data);
  14350. }, undefined, scene.database, true, onerror);
  14351. return texture;
  14352. };
  14353. ;
  14354. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14355. if (compression === void 0) { compression = null; }
  14356. var internalFormat = this._getInternalFormat(format);
  14357. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14358. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14359. if (!this._doNotHandleContextLost) {
  14360. texture._bufferView = data;
  14361. texture.format = format;
  14362. texture.invertY = invertY;
  14363. texture._compression = compression;
  14364. }
  14365. if (texture.width % 4 !== 0) {
  14366. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14367. }
  14368. if (compression && data) {
  14369. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14370. }
  14371. else {
  14372. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14373. }
  14374. if (texture.generateMipMaps) {
  14375. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14376. }
  14377. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14378. // this.resetTextureCache();
  14379. texture.isReady = true;
  14380. };
  14381. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14382. if (compression === void 0) { compression = null; }
  14383. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14384. texture.baseWidth = width;
  14385. texture.baseHeight = height;
  14386. texture.baseDepth = depth;
  14387. texture.width = width;
  14388. texture.height = height;
  14389. texture.depth = depth;
  14390. texture.format = format;
  14391. texture.generateMipMaps = generateMipMaps;
  14392. texture.samplingMode = samplingMode;
  14393. texture.is3D = true;
  14394. if (!this._doNotHandleContextLost) {
  14395. texture._bufferView = data;
  14396. }
  14397. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14398. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14399. // Filters
  14400. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14401. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14402. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14403. if (generateMipMaps) {
  14404. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14405. }
  14406. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14407. this._internalTexturesCache.push(texture);
  14408. return texture;
  14409. };
  14410. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14411. var gl = this._gl;
  14412. if (!gl) {
  14413. return;
  14414. }
  14415. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14416. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14417. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14418. if (!noMipmap && !isCompressed) {
  14419. gl.generateMipmap(gl.TEXTURE_2D);
  14420. }
  14421. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14422. // this.resetTextureCache();
  14423. if (scene) {
  14424. scene._removePendingData(texture);
  14425. }
  14426. texture.onLoadedObservable.notifyObservers(texture);
  14427. texture.onLoadedObservable.clear();
  14428. };
  14429. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14430. var _this = this;
  14431. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14432. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14433. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14434. var gl = this._gl;
  14435. if (!gl) {
  14436. return;
  14437. }
  14438. if (!texture._webGLTexture) {
  14439. // this.resetTextureCache();
  14440. if (scene) {
  14441. scene._removePendingData(texture);
  14442. }
  14443. return;
  14444. }
  14445. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14446. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14447. texture.baseWidth = width;
  14448. texture.baseHeight = height;
  14449. texture.width = potWidth;
  14450. texture.height = potHeight;
  14451. texture.isReady = true;
  14452. if (processFunction(potWidth, potHeight, function () {
  14453. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14454. })) {
  14455. // Returning as texture needs extra async steps
  14456. return;
  14457. }
  14458. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14459. };
  14460. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14461. // Create new RGBA data container.
  14462. var rgbaData;
  14463. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14464. rgbaData = new Float32Array(width * height * 4);
  14465. }
  14466. else {
  14467. rgbaData = new Uint32Array(width * height * 4);
  14468. }
  14469. // Convert each pixel.
  14470. for (var x = 0; x < width; x++) {
  14471. for (var y = 0; y < height; y++) {
  14472. var index = (y * width + x) * 3;
  14473. var newIndex = (y * width + x) * 4;
  14474. // Map Old Value to new value.
  14475. rgbaData[newIndex + 0] = rgbData[index + 0];
  14476. rgbaData[newIndex + 1] = rgbData[index + 1];
  14477. rgbaData[newIndex + 2] = rgbData[index + 2];
  14478. // Add fully opaque alpha channel.
  14479. rgbaData[newIndex + 3] = 1;
  14480. }
  14481. }
  14482. return rgbaData;
  14483. };
  14484. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14485. var gl = this._gl;
  14486. if (texture._framebuffer) {
  14487. gl.deleteFramebuffer(texture._framebuffer);
  14488. texture._framebuffer = null;
  14489. }
  14490. if (texture._depthStencilBuffer) {
  14491. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14492. texture._depthStencilBuffer = null;
  14493. }
  14494. if (texture._MSAAFramebuffer) {
  14495. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14496. texture._MSAAFramebuffer = null;
  14497. }
  14498. if (texture._MSAARenderBuffer) {
  14499. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14500. texture._MSAARenderBuffer = null;
  14501. }
  14502. };
  14503. Engine.prototype._releaseTexture = function (texture) {
  14504. var gl = this._gl;
  14505. this._releaseFramebufferObjects(texture);
  14506. gl.deleteTexture(texture._webGLTexture);
  14507. // Unbind channels
  14508. this.unbindAllTextures();
  14509. var index = this._internalTexturesCache.indexOf(texture);
  14510. if (index !== -1) {
  14511. this._internalTexturesCache.splice(index, 1);
  14512. }
  14513. // Integrated fixed lod samplers.
  14514. if (texture._lodTextureHigh) {
  14515. texture._lodTextureHigh.dispose();
  14516. }
  14517. if (texture._lodTextureMid) {
  14518. texture._lodTextureMid.dispose();
  14519. }
  14520. if (texture._lodTextureLow) {
  14521. texture._lodTextureLow.dispose();
  14522. }
  14523. // Set output texture of post process to null if the texture has been released/disposed
  14524. this.scenes.forEach(function (scene) {
  14525. scene.postProcesses.forEach(function (postProcess) {
  14526. if (postProcess._outputTexture == texture) {
  14527. postProcess._outputTexture = null;
  14528. }
  14529. });
  14530. scene.cameras.forEach(function (camera) {
  14531. camera._postProcesses.forEach(function (postProcess) {
  14532. if (postProcess) {
  14533. if (postProcess._outputTexture == texture) {
  14534. postProcess._outputTexture = null;
  14535. }
  14536. }
  14537. });
  14538. });
  14539. });
  14540. };
  14541. Engine.prototype.setProgram = function (program) {
  14542. if (this._currentProgram !== program) {
  14543. this._gl.useProgram(program);
  14544. this._currentProgram = program;
  14545. }
  14546. };
  14547. Engine.prototype.bindSamplers = function (effect) {
  14548. this.setProgram(effect.getProgram());
  14549. var samplers = effect.getSamplers();
  14550. for (var index = 0; index < samplers.length; index++) {
  14551. var uniform = effect.getUniform(samplers[index]);
  14552. if (uniform) {
  14553. this._boundUniforms[index] = uniform;
  14554. }
  14555. }
  14556. this._currentEffect = null;
  14557. };
  14558. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14559. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14560. return;
  14561. }
  14562. // Remove
  14563. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14564. // Bind last to it
  14565. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14566. // Bind to dummy
  14567. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14568. };
  14569. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14570. if (!internalTexture) {
  14571. return -1;
  14572. }
  14573. internalTexture._initialSlot = channel;
  14574. if (this.disableTextureBindingOptimization) {
  14575. if (channel !== internalTexture._designatedSlot) {
  14576. this._textureCollisions.addCount(1, false);
  14577. }
  14578. }
  14579. else {
  14580. if (channel !== internalTexture._designatedSlot) {
  14581. if (internalTexture._designatedSlot > -1) {
  14582. return internalTexture._designatedSlot;
  14583. }
  14584. else {
  14585. // No slot for this texture, let's pick a new one (if we find a free slot)
  14586. if (this._nextFreeTextureSlots.length) {
  14587. return this._nextFreeTextureSlots[0];
  14588. }
  14589. // We need to recycle the oldest bound texture, sorry.
  14590. this._textureCollisions.addCount(1, false);
  14591. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14592. }
  14593. }
  14594. }
  14595. return channel;
  14596. };
  14597. Engine.prototype._linkTrackers = function (previous, next) {
  14598. previous.next = next;
  14599. next.previous = previous;
  14600. };
  14601. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14602. var currentSlot = internalTexture._designatedSlot;
  14603. if (currentSlot === -1) {
  14604. return -1;
  14605. }
  14606. internalTexture._designatedSlot = -1;
  14607. if (this.disableTextureBindingOptimization) {
  14608. return -1;
  14609. }
  14610. // Remove from bound list
  14611. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14612. // Free the slot
  14613. this._boundTexturesCache[currentSlot] = null;
  14614. this._nextFreeTextureSlots.push(currentSlot);
  14615. return currentSlot;
  14616. };
  14617. Engine.prototype._activateCurrentTexture = function () {
  14618. if (this._currentTextureChannel !== this._activeChannel) {
  14619. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14620. this._currentTextureChannel = this._activeChannel;
  14621. }
  14622. };
  14623. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14624. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14625. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14626. this._activeChannel = texture._designatedSlot;
  14627. }
  14628. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14629. var isTextureForRendering = texture && texture._initialSlot > -1;
  14630. if (currentTextureBound !== texture) {
  14631. if (currentTextureBound) {
  14632. this._removeDesignatedSlot(currentTextureBound);
  14633. }
  14634. this._activateCurrentTexture();
  14635. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14636. this._boundTexturesCache[this._activeChannel] = texture;
  14637. if (texture) {
  14638. if (!this.disableTextureBindingOptimization) {
  14639. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14640. if (slotIndex > -1) {
  14641. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14642. }
  14643. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14644. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14645. }
  14646. texture._designatedSlot = this._activeChannel;
  14647. }
  14648. }
  14649. else if (forTextureDataUpdate) {
  14650. this._activateCurrentTexture();
  14651. }
  14652. if (isTextureForRendering && !forTextureDataUpdate) {
  14653. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14654. }
  14655. };
  14656. Engine.prototype._bindTexture = function (channel, texture) {
  14657. if (channel < 0) {
  14658. return;
  14659. }
  14660. if (texture) {
  14661. channel = this._getCorrectTextureChannel(channel, texture);
  14662. }
  14663. this._activeChannel = channel;
  14664. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14665. };
  14666. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14667. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14668. };
  14669. /**
  14670. * Binds the output of the passed in post process to the texture channel specified
  14671. * @param channel The channel the texture should be bound to
  14672. * @param postProcess The post process which's output should be bound
  14673. */
  14674. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  14675. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  14676. };
  14677. Engine.prototype.unbindAllTextures = function () {
  14678. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14679. this._activeChannel = channel;
  14680. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14681. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14682. if (this.webGLVersion > 1) {
  14683. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14684. }
  14685. }
  14686. };
  14687. /**
  14688. * Sets a texture to the according uniform.
  14689. * @param channel The texture channel
  14690. * @param uniform The uniform to set
  14691. * @param texture The texture to apply
  14692. */
  14693. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14694. if (channel < 0) {
  14695. return;
  14696. }
  14697. if (uniform) {
  14698. this._boundUniforms[channel] = uniform;
  14699. }
  14700. this._setTexture(channel, texture);
  14701. };
  14702. /**
  14703. * Sets a depth stencil texture from a render target to the according uniform.
  14704. * @param channel The texture channel
  14705. * @param uniform The uniform to set
  14706. * @param texture The render target texture containing the depth stencil texture to apply
  14707. */
  14708. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  14709. if (channel < 0) {
  14710. return;
  14711. }
  14712. if (uniform) {
  14713. this._boundUniforms[channel] = uniform;
  14714. }
  14715. if (!texture || !texture.depthStencilTexture) {
  14716. this._setTexture(channel, null);
  14717. }
  14718. else {
  14719. this._setTexture(channel, texture, false, true);
  14720. }
  14721. };
  14722. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14723. var uniform = this._boundUniforms[sourceSlot];
  14724. if (uniform._currentState === destination) {
  14725. return;
  14726. }
  14727. this._gl.uniform1i(uniform, destination);
  14728. uniform._currentState = destination;
  14729. };
  14730. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  14731. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14732. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  14733. // Not ready?
  14734. if (!texture) {
  14735. if (this._boundTexturesCache[channel] != null) {
  14736. this._activeChannel = channel;
  14737. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14738. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14739. if (this.webGLVersion > 1) {
  14740. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14741. }
  14742. }
  14743. return false;
  14744. }
  14745. // Video
  14746. if (texture.video) {
  14747. this._activeChannel = channel;
  14748. texture.update();
  14749. }
  14750. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14751. texture.delayLoad();
  14752. return false;
  14753. }
  14754. var internalTexture;
  14755. if (depthStencilTexture) {
  14756. internalTexture = texture.depthStencilTexture;
  14757. }
  14758. else if (texture.isReady()) {
  14759. internalTexture = texture.getInternalTexture();
  14760. }
  14761. else if (texture.isCube) {
  14762. internalTexture = this.emptyCubeTexture;
  14763. }
  14764. else if (texture.is3D) {
  14765. internalTexture = this.emptyTexture3D;
  14766. }
  14767. else {
  14768. internalTexture = this.emptyTexture;
  14769. }
  14770. if (!isPartOfTextureArray) {
  14771. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14772. }
  14773. if (this._boundTexturesCache[channel] === internalTexture) {
  14774. this._moveBoundTextureOnTop(internalTexture);
  14775. if (!isPartOfTextureArray) {
  14776. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14777. }
  14778. return false;
  14779. }
  14780. this._activeChannel = channel;
  14781. if (internalTexture && internalTexture.is3D) {
  14782. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14783. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14784. internalTexture._cachedWrapU = texture.wrapU;
  14785. switch (texture.wrapU) {
  14786. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14787. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14788. break;
  14789. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14790. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14791. break;
  14792. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14793. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14794. break;
  14795. }
  14796. }
  14797. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14798. internalTexture._cachedWrapV = texture.wrapV;
  14799. switch (texture.wrapV) {
  14800. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14801. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14802. break;
  14803. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14804. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14805. break;
  14806. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14807. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14808. break;
  14809. }
  14810. }
  14811. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14812. internalTexture._cachedWrapR = texture.wrapR;
  14813. switch (texture.wrapR) {
  14814. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14815. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14816. break;
  14817. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14818. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14819. break;
  14820. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14821. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14822. break;
  14823. }
  14824. }
  14825. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14826. }
  14827. else if (internalTexture && internalTexture.isCube) {
  14828. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14829. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14830. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14831. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14832. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14833. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14834. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14835. }
  14836. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14837. }
  14838. else {
  14839. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14840. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14841. internalTexture._cachedWrapU = texture.wrapU;
  14842. switch (texture.wrapU) {
  14843. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14844. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14845. break;
  14846. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14847. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14848. break;
  14849. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14850. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14851. break;
  14852. }
  14853. }
  14854. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14855. internalTexture._cachedWrapV = texture.wrapV;
  14856. switch (texture.wrapV) {
  14857. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14858. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14859. break;
  14860. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14861. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14862. break;
  14863. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14864. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14865. break;
  14866. }
  14867. }
  14868. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14869. }
  14870. return true;
  14871. };
  14872. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14873. if (channel < 0 || !uniform) {
  14874. return;
  14875. }
  14876. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14877. this._textureUnits = new Int32Array(textures.length);
  14878. }
  14879. for (var i = 0; i < textures.length; i++) {
  14880. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14881. }
  14882. this._gl.uniform1iv(uniform, this._textureUnits);
  14883. for (var index = 0; index < textures.length; index++) {
  14884. this._setTexture(this._textureUnits[index], textures[index], true);
  14885. }
  14886. };
  14887. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14888. var internalTexture = texture.getInternalTexture();
  14889. if (!internalTexture) {
  14890. return;
  14891. }
  14892. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14893. var value = texture.anisotropicFilteringLevel;
  14894. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14895. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14896. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14897. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14898. }
  14899. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14900. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14901. internalTexture._cachedAnisotropicFilteringLevel = value;
  14902. }
  14903. };
  14904. Engine.prototype.readPixels = function (x, y, width, height) {
  14905. var data = new Uint8Array(height * width * 4);
  14906. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14907. return data;
  14908. };
  14909. /**
  14910. * Add an externaly attached data from its key.
  14911. * This method call will fail and return false, if such key already exists.
  14912. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14913. * @param key the unique key that identifies the data
  14914. * @param data the data object to associate to the key for this Engine instance
  14915. * @return true if no such key were already present and the data was added successfully, false otherwise
  14916. */
  14917. Engine.prototype.addExternalData = function (key, data) {
  14918. if (!this._externalData) {
  14919. this._externalData = new BABYLON.StringDictionary();
  14920. }
  14921. return this._externalData.add(key, data);
  14922. };
  14923. /**
  14924. * Get an externaly attached data from its key
  14925. * @param key the unique key that identifies the data
  14926. * @return the associated data, if present (can be null), or undefined if not present
  14927. */
  14928. Engine.prototype.getExternalData = function (key) {
  14929. if (!this._externalData) {
  14930. this._externalData = new BABYLON.StringDictionary();
  14931. }
  14932. return this._externalData.get(key);
  14933. };
  14934. /**
  14935. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14936. * @param key the unique key that identifies the data
  14937. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14938. * @return the associated data, can be null if the factory returned null.
  14939. */
  14940. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14941. if (!this._externalData) {
  14942. this._externalData = new BABYLON.StringDictionary();
  14943. }
  14944. return this._externalData.getOrAddWithFactory(key, factory);
  14945. };
  14946. /**
  14947. * Remove an externaly attached data from the Engine instance
  14948. * @param key the unique key that identifies the data
  14949. * @return true if the data was successfully removed, false if it doesn't exist
  14950. */
  14951. Engine.prototype.removeExternalData = function (key) {
  14952. if (!this._externalData) {
  14953. this._externalData = new BABYLON.StringDictionary();
  14954. }
  14955. return this._externalData.remove(key);
  14956. };
  14957. Engine.prototype.unbindAllAttributes = function () {
  14958. if (this._mustWipeVertexAttributes) {
  14959. this._mustWipeVertexAttributes = false;
  14960. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14961. this._gl.disableVertexAttribArray(i);
  14962. this._vertexAttribArraysEnabled[i] = false;
  14963. this._currentBufferPointers[i].active = false;
  14964. }
  14965. return;
  14966. }
  14967. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14968. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14969. continue;
  14970. }
  14971. this._gl.disableVertexAttribArray(i);
  14972. this._vertexAttribArraysEnabled[i] = false;
  14973. this._currentBufferPointers[i].active = false;
  14974. }
  14975. };
  14976. Engine.prototype.releaseEffects = function () {
  14977. for (var name in this._compiledEffects) {
  14978. this._deleteProgram(this._compiledEffects[name]._program);
  14979. }
  14980. this._compiledEffects = {};
  14981. };
  14982. // Dispose
  14983. Engine.prototype.dispose = function () {
  14984. this.hideLoadingUI();
  14985. this.stopRenderLoop();
  14986. // Release postProcesses
  14987. while (this.postProcesses.length) {
  14988. this.postProcesses[0].dispose();
  14989. }
  14990. // Empty texture
  14991. if (this._emptyTexture) {
  14992. this._releaseTexture(this._emptyTexture);
  14993. this._emptyTexture = null;
  14994. }
  14995. if (this._emptyCubeTexture) {
  14996. this._releaseTexture(this._emptyCubeTexture);
  14997. this._emptyCubeTexture = null;
  14998. }
  14999. // Rescale PP
  15000. if (this._rescalePostProcess) {
  15001. this._rescalePostProcess.dispose();
  15002. }
  15003. // Release scenes
  15004. while (this.scenes.length) {
  15005. this.scenes[0].dispose();
  15006. }
  15007. // Release audio engine
  15008. if (Engine.audioEngine) {
  15009. Engine.audioEngine.dispose();
  15010. }
  15011. // Release effects
  15012. this.releaseEffects();
  15013. // Unbind
  15014. this.unbindAllAttributes();
  15015. this._boundUniforms = [];
  15016. if (this._dummyFramebuffer) {
  15017. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  15018. }
  15019. //WebVR
  15020. this.disableVR();
  15021. // Events
  15022. if (BABYLON.Tools.IsWindowObjectExist()) {
  15023. window.removeEventListener("blur", this._onBlur);
  15024. window.removeEventListener("focus", this._onFocus);
  15025. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  15026. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  15027. if (this._renderingCanvas) {
  15028. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  15029. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  15030. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  15031. if (!this._doNotHandleContextLost) {
  15032. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  15033. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  15034. }
  15035. }
  15036. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  15037. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  15038. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  15039. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  15040. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  15041. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  15042. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  15043. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  15044. if (this._onVrDisplayConnect) {
  15045. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  15046. if (this._onVrDisplayDisconnect) {
  15047. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  15048. }
  15049. if (this._onVrDisplayPresentChange) {
  15050. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  15051. }
  15052. this._onVrDisplayConnect = null;
  15053. this._onVrDisplayDisconnect = null;
  15054. }
  15055. }
  15056. // Remove from Instances
  15057. var index = Engine.Instances.indexOf(this);
  15058. if (index >= 0) {
  15059. Engine.Instances.splice(index, 1);
  15060. }
  15061. this._workingCanvas = null;
  15062. this._workingContext = null;
  15063. this._currentBufferPointers = [];
  15064. this._renderingCanvas = null;
  15065. this._currentProgram = null;
  15066. this._bindedRenderFunction = null;
  15067. this.onResizeObservable.clear();
  15068. this.onCanvasBlurObservable.clear();
  15069. this.onCanvasFocusObservable.clear();
  15070. this.onCanvasPointerOutObservable.clear();
  15071. this.onBeginFrameObservable.clear();
  15072. this.onEndFrameObservable.clear();
  15073. BABYLON.Effect.ResetCache();
  15074. // Abort active requests
  15075. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  15076. var request = _a[_i];
  15077. request.abort();
  15078. }
  15079. };
  15080. // Loading screen
  15081. Engine.prototype.displayLoadingUI = function () {
  15082. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15083. return;
  15084. }
  15085. var loadingScreen = this.loadingScreen;
  15086. if (loadingScreen) {
  15087. loadingScreen.displayLoadingUI();
  15088. }
  15089. };
  15090. Engine.prototype.hideLoadingUI = function () {
  15091. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15092. return;
  15093. }
  15094. var loadingScreen = this.loadingScreen;
  15095. if (loadingScreen) {
  15096. loadingScreen.hideLoadingUI();
  15097. }
  15098. };
  15099. Object.defineProperty(Engine.prototype, "loadingScreen", {
  15100. get: function () {
  15101. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  15102. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  15103. return this._loadingScreen;
  15104. },
  15105. set: function (loadingScreen) {
  15106. this._loadingScreen = loadingScreen;
  15107. },
  15108. enumerable: true,
  15109. configurable: true
  15110. });
  15111. Object.defineProperty(Engine.prototype, "loadingUIText", {
  15112. set: function (text) {
  15113. this.loadingScreen.loadingUIText = text;
  15114. },
  15115. enumerable: true,
  15116. configurable: true
  15117. });
  15118. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  15119. set: function (color) {
  15120. this.loadingScreen.loadingUIBackgroundColor = color;
  15121. },
  15122. enumerable: true,
  15123. configurable: true
  15124. });
  15125. Engine.prototype.attachContextLostEvent = function (callback) {
  15126. if (this._renderingCanvas) {
  15127. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  15128. }
  15129. };
  15130. Engine.prototype.attachContextRestoredEvent = function (callback) {
  15131. if (this._renderingCanvas) {
  15132. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  15133. }
  15134. };
  15135. Engine.prototype.getVertexShaderSource = function (program) {
  15136. var shaders = this._gl.getAttachedShaders(program);
  15137. if (!shaders) {
  15138. return null;
  15139. }
  15140. return this._gl.getShaderSource(shaders[0]);
  15141. };
  15142. Engine.prototype.getFragmentShaderSource = function (program) {
  15143. var shaders = this._gl.getAttachedShaders(program);
  15144. if (!shaders) {
  15145. return null;
  15146. }
  15147. return this._gl.getShaderSource(shaders[1]);
  15148. };
  15149. Engine.prototype.getError = function () {
  15150. return this._gl.getError();
  15151. };
  15152. // FPS
  15153. Engine.prototype.getFps = function () {
  15154. return this._fps;
  15155. };
  15156. Engine.prototype.getDeltaTime = function () {
  15157. return this._deltaTime;
  15158. };
  15159. Engine.prototype._measureFps = function () {
  15160. this._performanceMonitor.sampleFrame();
  15161. this._fps = this._performanceMonitor.averageFPS;
  15162. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  15163. };
  15164. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  15165. if (faceIndex === void 0) { faceIndex = -1; }
  15166. var gl = this._gl;
  15167. if (!this._dummyFramebuffer) {
  15168. var dummy = gl.createFramebuffer();
  15169. if (!dummy) {
  15170. throw new Error("Unable to create dummy framebuffer");
  15171. }
  15172. this._dummyFramebuffer = dummy;
  15173. }
  15174. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  15175. if (faceIndex > -1) {
  15176. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  15177. }
  15178. else {
  15179. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15180. }
  15181. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  15182. var buffer;
  15183. switch (readType) {
  15184. case gl.UNSIGNED_BYTE:
  15185. buffer = new Uint8Array(4 * width * height);
  15186. readType = gl.UNSIGNED_BYTE;
  15187. break;
  15188. default:
  15189. buffer = new Float32Array(4 * width * height);
  15190. readType = gl.FLOAT;
  15191. break;
  15192. }
  15193. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  15194. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  15195. return buffer;
  15196. };
  15197. Engine.prototype._canRenderToFloatFramebuffer = function () {
  15198. if (this._webGLVersion > 1) {
  15199. return this._caps.colorBufferFloat;
  15200. }
  15201. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  15202. };
  15203. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  15204. if (this._webGLVersion > 1) {
  15205. return this._caps.colorBufferFloat;
  15206. }
  15207. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  15208. };
  15209. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  15210. Engine.prototype._canRenderToFramebuffer = function (type) {
  15211. var gl = this._gl;
  15212. //clear existing errors
  15213. while (gl.getError() !== gl.NO_ERROR) { }
  15214. var successful = true;
  15215. var texture = gl.createTexture();
  15216. gl.bindTexture(gl.TEXTURE_2D, texture);
  15217. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15218. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15219. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15220. var fb = gl.createFramebuffer();
  15221. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  15222. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  15223. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  15224. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  15225. successful = successful && (gl.getError() === gl.NO_ERROR);
  15226. //try render by clearing frame buffer's color buffer
  15227. if (successful) {
  15228. gl.clear(gl.COLOR_BUFFER_BIT);
  15229. successful = successful && (gl.getError() === gl.NO_ERROR);
  15230. }
  15231. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  15232. if (successful) {
  15233. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  15234. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15235. var readFormat = gl.RGBA;
  15236. var readType = gl.UNSIGNED_BYTE;
  15237. var buffer = new Uint8Array(4);
  15238. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  15239. successful = successful && (gl.getError() === gl.NO_ERROR);
  15240. }
  15241. //clean up
  15242. gl.deleteTexture(texture);
  15243. gl.deleteFramebuffer(fb);
  15244. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15245. //clear accumulated errors
  15246. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  15247. return successful;
  15248. };
  15249. Engine.prototype._getWebGLTextureType = function (type) {
  15250. if (type === Engine.TEXTURETYPE_FLOAT) {
  15251. return this._gl.FLOAT;
  15252. }
  15253. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15254. // Add Half Float Constant.
  15255. return this._gl.HALF_FLOAT_OES;
  15256. }
  15257. return this._gl.UNSIGNED_BYTE;
  15258. };
  15259. ;
  15260. Engine.prototype._getInternalFormat = function (format) {
  15261. var internalFormat = this._gl.RGBA;
  15262. switch (format) {
  15263. case Engine.TEXTUREFORMAT_ALPHA:
  15264. internalFormat = this._gl.ALPHA;
  15265. break;
  15266. case Engine.TEXTUREFORMAT_LUMINANCE:
  15267. internalFormat = this._gl.LUMINANCE;
  15268. break;
  15269. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  15270. internalFormat = this._gl.LUMINANCE_ALPHA;
  15271. break;
  15272. case Engine.TEXTUREFORMAT_RGB:
  15273. case Engine.TEXTUREFORMAT_RGB32F:
  15274. internalFormat = this._gl.RGB;
  15275. break;
  15276. case Engine.TEXTUREFORMAT_RGBA:
  15277. case Engine.TEXTUREFORMAT_RGBA32F:
  15278. internalFormat = this._gl.RGBA;
  15279. break;
  15280. case Engine.TEXTUREFORMAT_R32F:
  15281. internalFormat = this._gl.RED;
  15282. break;
  15283. case Engine.TEXTUREFORMAT_RG32F:
  15284. internalFormat = this._gl.RG;
  15285. break;
  15286. }
  15287. return internalFormat;
  15288. };
  15289. /** @ignore */
  15290. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15291. if (this._webGLVersion === 1) {
  15292. if (format) {
  15293. switch (format) {
  15294. case Engine.TEXTUREFORMAT_LUMINANCE:
  15295. return this._gl.LUMINANCE;
  15296. }
  15297. }
  15298. return this._gl.RGBA;
  15299. }
  15300. if (type === Engine.TEXTURETYPE_FLOAT) {
  15301. if (format) {
  15302. switch (format) {
  15303. case Engine.TEXTUREFORMAT_R32F:
  15304. return this._gl.R32F;
  15305. case Engine.TEXTUREFORMAT_RG32F:
  15306. return this._gl.RG32F;
  15307. case Engine.TEXTUREFORMAT_RGB32F:
  15308. return this._gl.RGB32F;
  15309. }
  15310. }
  15311. return this._gl.RGBA32F;
  15312. }
  15313. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15314. return this._gl.RGBA16F;
  15315. }
  15316. if (format) {
  15317. switch (format) {
  15318. case Engine.TEXTUREFORMAT_LUMINANCE:
  15319. return this._gl.LUMINANCE;
  15320. }
  15321. }
  15322. return this._gl.RGBA;
  15323. };
  15324. ;
  15325. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15326. if (type === Engine.TEXTURETYPE_FLOAT) {
  15327. return this._gl.RGBA32F;
  15328. }
  15329. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15330. return this._gl.RGBA16F;
  15331. }
  15332. return this._gl.RGBA8;
  15333. };
  15334. ;
  15335. Engine.prototype.createQuery = function () {
  15336. return this._gl.createQuery();
  15337. };
  15338. Engine.prototype.deleteQuery = function (query) {
  15339. this._gl.deleteQuery(query);
  15340. return this;
  15341. };
  15342. Engine.prototype.isQueryResultAvailable = function (query) {
  15343. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15344. };
  15345. Engine.prototype.getQueryResult = function (query) {
  15346. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15347. };
  15348. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15349. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15350. this._gl.beginQuery(glAlgorithm, query);
  15351. return this;
  15352. };
  15353. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15354. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15355. this._gl.endQuery(glAlgorithm);
  15356. return this;
  15357. };
  15358. /* Time queries */
  15359. Engine.prototype._createTimeQuery = function () {
  15360. var timerQuery = this._caps.timerQuery;
  15361. if (timerQuery.createQueryEXT) {
  15362. return timerQuery.createQueryEXT();
  15363. }
  15364. return this.createQuery();
  15365. };
  15366. Engine.prototype._deleteTimeQuery = function (query) {
  15367. var timerQuery = this._caps.timerQuery;
  15368. if (timerQuery.deleteQueryEXT) {
  15369. timerQuery.deleteQueryEXT(query);
  15370. return;
  15371. }
  15372. this.deleteQuery(query);
  15373. };
  15374. Engine.prototype._getTimeQueryResult = function (query) {
  15375. var timerQuery = this._caps.timerQuery;
  15376. if (timerQuery.getQueryObjectEXT) {
  15377. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15378. }
  15379. return this.getQueryResult(query);
  15380. };
  15381. Engine.prototype._getTimeQueryAvailability = function (query) {
  15382. var timerQuery = this._caps.timerQuery;
  15383. if (timerQuery.getQueryObjectEXT) {
  15384. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15385. }
  15386. return this.isQueryResultAvailable(query);
  15387. };
  15388. Engine.prototype.startTimeQuery = function () {
  15389. var timerQuery = this._caps.timerQuery;
  15390. if (!timerQuery) {
  15391. return null;
  15392. }
  15393. var token = new BABYLON._TimeToken();
  15394. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15395. if (this._caps.canUseTimestampForTimerQuery) {
  15396. token._startTimeQuery = this._createTimeQuery();
  15397. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15398. }
  15399. else {
  15400. if (this._currentNonTimestampToken) {
  15401. return this._currentNonTimestampToken;
  15402. }
  15403. token._timeElapsedQuery = this._createTimeQuery();
  15404. if (timerQuery.beginQueryEXT) {
  15405. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15406. }
  15407. else {
  15408. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15409. }
  15410. this._currentNonTimestampToken = token;
  15411. }
  15412. return token;
  15413. };
  15414. Engine.prototype.endTimeQuery = function (token) {
  15415. var timerQuery = this._caps.timerQuery;
  15416. if (!timerQuery || !token) {
  15417. return -1;
  15418. }
  15419. if (this._caps.canUseTimestampForTimerQuery) {
  15420. if (!token._startTimeQuery) {
  15421. return -1;
  15422. }
  15423. if (!token._endTimeQuery) {
  15424. token._endTimeQuery = this._createTimeQuery();
  15425. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15426. }
  15427. }
  15428. else if (!token._timeElapsedQueryEnded) {
  15429. if (!token._timeElapsedQuery) {
  15430. return -1;
  15431. }
  15432. if (timerQuery.endQueryEXT) {
  15433. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15434. }
  15435. else {
  15436. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15437. }
  15438. token._timeElapsedQueryEnded = true;
  15439. }
  15440. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15441. var available = false;
  15442. if (token._endTimeQuery) {
  15443. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15444. }
  15445. else if (token._timeElapsedQuery) {
  15446. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15447. }
  15448. if (available && !disjoint) {
  15449. var result = 0;
  15450. if (this._caps.canUseTimestampForTimerQuery) {
  15451. if (!token._startTimeQuery || !token._endTimeQuery) {
  15452. return -1;
  15453. }
  15454. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15455. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15456. result = timeEnd - timeStart;
  15457. this._deleteTimeQuery(token._startTimeQuery);
  15458. this._deleteTimeQuery(token._endTimeQuery);
  15459. token._startTimeQuery = null;
  15460. token._endTimeQuery = null;
  15461. }
  15462. else {
  15463. if (!token._timeElapsedQuery) {
  15464. return -1;
  15465. }
  15466. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15467. this._deleteTimeQuery(token._timeElapsedQuery);
  15468. token._timeElapsedQuery = null;
  15469. token._timeElapsedQueryEnded = false;
  15470. this._currentNonTimestampToken = null;
  15471. }
  15472. return result;
  15473. }
  15474. return -1;
  15475. };
  15476. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15477. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15478. };
  15479. // Transform feedback
  15480. Engine.prototype.createTransformFeedback = function () {
  15481. return this._gl.createTransformFeedback();
  15482. };
  15483. Engine.prototype.deleteTransformFeedback = function (value) {
  15484. this._gl.deleteTransformFeedback(value);
  15485. };
  15486. Engine.prototype.bindTransformFeedback = function (value) {
  15487. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15488. };
  15489. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15490. if (usePoints === void 0) { usePoints = true; }
  15491. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15492. };
  15493. Engine.prototype.endTransformFeedback = function () {
  15494. this._gl.endTransformFeedback();
  15495. };
  15496. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15497. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15498. };
  15499. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15500. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15501. };
  15502. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15503. var _this = this;
  15504. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15505. this._activeRequests.push(request);
  15506. request.onCompleteObservable.add(function (request) {
  15507. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15508. });
  15509. return request;
  15510. };
  15511. /** @ignore */
  15512. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15513. var _this = this;
  15514. return new Promise(function (resolve, reject) {
  15515. _this._loadFile(url, function (data) {
  15516. resolve(data);
  15517. }, undefined, database, useArrayBuffer, function (request, exception) {
  15518. reject(exception);
  15519. });
  15520. });
  15521. };
  15522. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15523. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15524. var onload = function (data) {
  15525. loadedFiles[index] = data;
  15526. loadedFiles._internalCount++;
  15527. if (loadedFiles._internalCount === 6) {
  15528. onfinish(loadedFiles);
  15529. }
  15530. };
  15531. var onerror = function (request, exception) {
  15532. if (onErrorCallBack && request) {
  15533. onErrorCallBack(request.status + " " + request.statusText, exception);
  15534. }
  15535. };
  15536. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15537. };
  15538. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15539. if (onError === void 0) { onError = null; }
  15540. var loadedFiles = [];
  15541. loadedFiles._internalCount = 0;
  15542. for (var index = 0; index < 6; index++) {
  15543. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15544. }
  15545. };
  15546. // Statics
  15547. Engine.isSupported = function () {
  15548. try {
  15549. var tempcanvas = document.createElement("canvas");
  15550. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15551. return gl != null && !!window.WebGLRenderingContext;
  15552. }
  15553. catch (e) {
  15554. return false;
  15555. }
  15556. };
  15557. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15558. Engine.ExceptionList = [
  15559. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15560. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15561. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15562. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15563. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15564. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15565. ];
  15566. Engine.Instances = new Array();
  15567. // Const statics
  15568. Engine._ALPHA_DISABLE = 0;
  15569. Engine._ALPHA_ADD = 1;
  15570. Engine._ALPHA_COMBINE = 2;
  15571. Engine._ALPHA_SUBTRACT = 3;
  15572. Engine._ALPHA_MULTIPLY = 4;
  15573. Engine._ALPHA_MAXIMIZED = 5;
  15574. Engine._ALPHA_ONEONE = 6;
  15575. Engine._ALPHA_PREMULTIPLIED = 7;
  15576. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15577. Engine._ALPHA_INTERPOLATE = 9;
  15578. Engine._ALPHA_SCREENMODE = 10;
  15579. Engine._DELAYLOADSTATE_NONE = 0;
  15580. Engine._DELAYLOADSTATE_LOADED = 1;
  15581. Engine._DELAYLOADSTATE_LOADING = 2;
  15582. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15583. Engine._TEXTUREFORMAT_ALPHA = 0;
  15584. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15585. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15586. Engine._TEXTUREFORMAT_RGB = 4;
  15587. Engine._TEXTUREFORMAT_RGBA = 5;
  15588. Engine._TEXTUREFORMAT_R32F = 6;
  15589. Engine._TEXTUREFORMAT_RG32F = 7;
  15590. Engine._TEXTUREFORMAT_RGB32F = 8;
  15591. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15592. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15593. Engine._TEXTURETYPE_FLOAT = 1;
  15594. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15595. // Depht or Stencil test Constants.
  15596. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15597. 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.
  15598. 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.
  15599. 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.
  15600. 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.
  15601. 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.
  15602. 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.
  15603. 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.
  15604. // Stencil Actions Constants.
  15605. Engine._KEEP = 0x1E00;
  15606. Engine._REPLACE = 0x1E01;
  15607. Engine._INCR = 0x1E02;
  15608. Engine._DECR = 0x1E03;
  15609. Engine._INVERT = 0x150A;
  15610. Engine._INCR_WRAP = 0x8507;
  15611. Engine._DECR_WRAP = 0x8508;
  15612. // Texture rescaling mode
  15613. Engine._SCALEMODE_FLOOR = 1;
  15614. Engine._SCALEMODE_NEAREST = 2;
  15615. Engine._SCALEMODE_CEILING = 3;
  15616. // Updatable statics so stick with vars here
  15617. Engine.CollisionsEpsilon = 0.001;
  15618. Engine.CodeRepository = "src/";
  15619. Engine.ShadersRepository = "src/Shaders/";
  15620. return Engine;
  15621. }());
  15622. BABYLON.Engine = Engine;
  15623. })(BABYLON || (BABYLON = {}));
  15624. //# sourceMappingURL=babylon.engine.js.map
  15625. "use strict";
  15626. var BABYLON;
  15627. (function (BABYLON) {
  15628. /**
  15629. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15630. */
  15631. var Node = /** @class */ (function () {
  15632. /**
  15633. * Creates a new Node
  15634. * @param {string} name - the name and id to be given to this node
  15635. * @param {BABYLON.Scene} the scene this node will be added to
  15636. */
  15637. function Node(name, scene) {
  15638. if (scene === void 0) { scene = null; }
  15639. /**
  15640. * Gets or sets a string used to store user defined state for the node
  15641. */
  15642. this.state = "";
  15643. /**
  15644. * Gets or sets an object used to store user defined information for the node
  15645. */
  15646. this.metadata = null;
  15647. /**
  15648. * Gets or sets a boolean used to define if the node must be serialized
  15649. */
  15650. this.doNotSerialize = false;
  15651. /** @ignore */
  15652. this._isDisposed = false;
  15653. /**
  15654. * Gets a list of {BABYLON.Animation} associated with the node
  15655. */
  15656. this.animations = new Array();
  15657. this._ranges = {};
  15658. this._isEnabled = true;
  15659. this._isReady = true;
  15660. /** @ignore */
  15661. this._currentRenderId = -1;
  15662. this._parentRenderId = -1;
  15663. this._animationPropertiesOverride = null;
  15664. /**
  15665. * An event triggered when the mesh is disposed
  15666. * @type {BABYLON.Observable}
  15667. */
  15668. this.onDisposeObservable = new BABYLON.Observable();
  15669. // Behaviors
  15670. this._behaviors = new Array();
  15671. this.name = name;
  15672. this.id = name;
  15673. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15674. this.uniqueId = this._scene.getUniqueId();
  15675. this._initCache();
  15676. }
  15677. /**
  15678. * Gets a boolean indicating if the node has been disposed
  15679. * @returns true if the node was disposed
  15680. */
  15681. Node.prototype.isDisposed = function () {
  15682. return this._isDisposed;
  15683. };
  15684. Object.defineProperty(Node.prototype, "parent", {
  15685. get: function () {
  15686. return this._parentNode;
  15687. },
  15688. /**
  15689. * Gets or sets the parent of the node
  15690. */
  15691. set: function (parent) {
  15692. if (this._parentNode === parent) {
  15693. return;
  15694. }
  15695. // Remove self from list of children of parent
  15696. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15697. var index = this._parentNode._children.indexOf(this);
  15698. if (index !== -1) {
  15699. this._parentNode._children.splice(index, 1);
  15700. }
  15701. }
  15702. // Store new parent
  15703. this._parentNode = parent;
  15704. // Add as child to new parent
  15705. if (this._parentNode) {
  15706. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15707. this._parentNode._children = new Array();
  15708. }
  15709. this._parentNode._children.push(this);
  15710. }
  15711. },
  15712. enumerable: true,
  15713. configurable: true
  15714. });
  15715. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15716. /**
  15717. * Gets or sets the animation properties override
  15718. */
  15719. get: function () {
  15720. return this._animationPropertiesOverride;
  15721. },
  15722. set: function (value) {
  15723. this._animationPropertiesOverride = value;
  15724. },
  15725. enumerable: true,
  15726. configurable: true
  15727. });
  15728. /**
  15729. * Gets a string idenfifying the name of the class
  15730. * @returns "Node" string
  15731. */
  15732. Node.prototype.getClassName = function () {
  15733. return "Node";
  15734. };
  15735. Object.defineProperty(Node.prototype, "onDispose", {
  15736. /**
  15737. * Sets a callback that will be raised when the node will be disposed
  15738. */
  15739. set: function (callback) {
  15740. if (this._onDisposeObserver) {
  15741. this.onDisposeObservable.remove(this._onDisposeObserver);
  15742. }
  15743. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15744. },
  15745. enumerable: true,
  15746. configurable: true
  15747. });
  15748. /**
  15749. * Gets the scene of the node
  15750. * @returns a {BABYLON.Scene}
  15751. */
  15752. Node.prototype.getScene = function () {
  15753. return this._scene;
  15754. };
  15755. /**
  15756. * Gets the engine of the node
  15757. * @returns a {BABYLON.Engine}
  15758. */
  15759. Node.prototype.getEngine = function () {
  15760. return this._scene.getEngine();
  15761. };
  15762. /**
  15763. * Attach a behavior to the node
  15764. * @see http://doc.babylonjs.com/features/behaviour
  15765. * @param behavior defines the behavior to attach
  15766. * @returns the current Node
  15767. */
  15768. Node.prototype.addBehavior = function (behavior) {
  15769. var _this = this;
  15770. var index = this._behaviors.indexOf(behavior);
  15771. if (index !== -1) {
  15772. return this;
  15773. }
  15774. behavior.init();
  15775. if (this._scene.isLoading) {
  15776. // We defer the attach when the scene will be loaded
  15777. var observer = this._scene.onDataLoadedObservable.add(function () {
  15778. behavior.attach(_this);
  15779. setTimeout(function () {
  15780. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15781. _this._scene.onDataLoadedObservable.remove(observer);
  15782. }, 0);
  15783. });
  15784. }
  15785. else {
  15786. behavior.attach(this);
  15787. }
  15788. this._behaviors.push(behavior);
  15789. return this;
  15790. };
  15791. /**
  15792. * Remove an attached behavior
  15793. * @see http://doc.babylonjs.com/features/behaviour
  15794. * @param behavior defines the behavior to attach
  15795. * @returns the current Node
  15796. */
  15797. Node.prototype.removeBehavior = function (behavior) {
  15798. var index = this._behaviors.indexOf(behavior);
  15799. if (index === -1) {
  15800. return this;
  15801. }
  15802. this._behaviors[index].detach();
  15803. this._behaviors.splice(index, 1);
  15804. return this;
  15805. };
  15806. Object.defineProperty(Node.prototype, "behaviors", {
  15807. /**
  15808. * Gets the list of attached behaviors
  15809. * @see http://doc.babylonjs.com/features/behaviour
  15810. */
  15811. get: function () {
  15812. return this._behaviors;
  15813. },
  15814. enumerable: true,
  15815. configurable: true
  15816. });
  15817. /**
  15818. * Gets an attached behavior by name
  15819. * @param name defines the name of the behavior to look for
  15820. * @see http://doc.babylonjs.com/features/behaviour
  15821. * @returns null if behavior was not found else the requested behavior
  15822. */
  15823. Node.prototype.getBehaviorByName = function (name) {
  15824. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15825. var behavior = _a[_i];
  15826. if (behavior.name === name) {
  15827. return behavior;
  15828. }
  15829. }
  15830. return null;
  15831. };
  15832. /**
  15833. * Returns the world matrix of the node
  15834. * @returns a matrix containing the node's world matrix
  15835. */
  15836. Node.prototype.getWorldMatrix = function () {
  15837. return BABYLON.Matrix.Identity();
  15838. };
  15839. // override it in derived class if you add new variables to the cache
  15840. // and call the parent class method
  15841. /** @ignore */
  15842. Node.prototype._initCache = function () {
  15843. this._cache = {};
  15844. this._cache.parent = undefined;
  15845. };
  15846. /** @ignore */
  15847. Node.prototype.updateCache = function (force) {
  15848. if (!force && this.isSynchronized())
  15849. return;
  15850. this._cache.parent = this.parent;
  15851. this._updateCache();
  15852. };
  15853. // override it in derived class if you add new variables to the cache
  15854. // and call the parent class method if !ignoreParentClass
  15855. /** @ignore */
  15856. Node.prototype._updateCache = function (ignoreParentClass) {
  15857. };
  15858. // override it in derived class if you add new variables to the cache
  15859. /** @ignore */
  15860. Node.prototype._isSynchronized = function () {
  15861. return true;
  15862. };
  15863. /** @ignore */
  15864. Node.prototype._markSyncedWithParent = function () {
  15865. if (this.parent) {
  15866. this._parentRenderId = this.parent._currentRenderId;
  15867. }
  15868. };
  15869. /** @ignore */
  15870. Node.prototype.isSynchronizedWithParent = function () {
  15871. if (!this.parent) {
  15872. return true;
  15873. }
  15874. if (this._parentRenderId !== this.parent._currentRenderId) {
  15875. return false;
  15876. }
  15877. return this.parent.isSynchronized();
  15878. };
  15879. /** @ignore */
  15880. Node.prototype.isSynchronized = function (updateCache) {
  15881. var check = this.hasNewParent();
  15882. check = check || !this.isSynchronizedWithParent();
  15883. check = check || !this._isSynchronized();
  15884. if (updateCache)
  15885. this.updateCache(true);
  15886. return !check;
  15887. };
  15888. /** @ignore */
  15889. Node.prototype.hasNewParent = function (update) {
  15890. if (this._cache.parent === this.parent)
  15891. return false;
  15892. if (update)
  15893. this._cache.parent = this.parent;
  15894. return true;
  15895. };
  15896. /**
  15897. * Is this node ready to be used/rendered
  15898. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15899. * @return true if the node is ready
  15900. */
  15901. Node.prototype.isReady = function (completeCheck) {
  15902. if (completeCheck === void 0) { completeCheck = false; }
  15903. return this._isReady;
  15904. };
  15905. /**
  15906. * Is this node enabled?
  15907. * 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
  15908. * @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
  15909. * @return whether this node (and its parent) is enabled
  15910. * @see setEnabled
  15911. */
  15912. Node.prototype.isEnabled = function (checkAncestors) {
  15913. if (checkAncestors === void 0) { checkAncestors = true; }
  15914. if (checkAncestors === false) {
  15915. return this._isEnabled;
  15916. }
  15917. if (this._isEnabled === false) {
  15918. return false;
  15919. }
  15920. if (this.parent !== undefined && this.parent !== null) {
  15921. return this.parent.isEnabled(checkAncestors);
  15922. }
  15923. return true;
  15924. };
  15925. /**
  15926. * Set the enabled state of this node
  15927. * @param value defines the new enabled state
  15928. * @see isEnabled
  15929. */
  15930. Node.prototype.setEnabled = function (value) {
  15931. this._isEnabled = value;
  15932. };
  15933. /**
  15934. * Is this node a descendant of the given node?
  15935. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15936. * @param ancestor defines the parent node to inspect
  15937. * @see parent
  15938. * @returns a boolean indicating if this node is a descendant of the given node
  15939. */
  15940. Node.prototype.isDescendantOf = function (ancestor) {
  15941. if (this.parent) {
  15942. if (this.parent === ancestor) {
  15943. return true;
  15944. }
  15945. return this.parent.isDescendantOf(ancestor);
  15946. }
  15947. return false;
  15948. };
  15949. /** @ignore */
  15950. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15951. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15952. if (!this._children) {
  15953. return;
  15954. }
  15955. for (var index = 0; index < this._children.length; index++) {
  15956. var item = this._children[index];
  15957. if (!predicate || predicate(item)) {
  15958. results.push(item);
  15959. }
  15960. if (!directDescendantsOnly) {
  15961. item._getDescendants(results, false, predicate);
  15962. }
  15963. }
  15964. };
  15965. /**
  15966. * Will return all nodes that have this node as ascendant
  15967. * @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
  15968. * @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
  15969. * @return all children nodes of all types
  15970. */
  15971. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15972. var results = new Array();
  15973. this._getDescendants(results, directDescendantsOnly, predicate);
  15974. return results;
  15975. };
  15976. /**
  15977. * Get all child-meshes of this node
  15978. * @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
  15979. * @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
  15980. * @returns an array of {BABYLON.AbstractMesh}
  15981. */
  15982. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15983. var results = [];
  15984. this._getDescendants(results, directDescendantsOnly, function (node) {
  15985. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15986. });
  15987. return results;
  15988. };
  15989. /**
  15990. * Get all child-transformNodes of this node
  15991. * @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
  15992. * @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
  15993. * @returns an array of {BABYLON.TransformNode}
  15994. */
  15995. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15996. var results = [];
  15997. this._getDescendants(results, directDescendantsOnly, function (node) {
  15998. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15999. });
  16000. return results;
  16001. };
  16002. /**
  16003. * Get all direct children of this node
  16004. * @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
  16005. * @returns an array of {BABYLON.Node}
  16006. */
  16007. Node.prototype.getChildren = function (predicate) {
  16008. return this.getDescendants(true, predicate);
  16009. };
  16010. /** @ignore */
  16011. Node.prototype._setReady = function (state) {
  16012. if (state === this._isReady) {
  16013. return;
  16014. }
  16015. if (!state) {
  16016. this._isReady = false;
  16017. return;
  16018. }
  16019. if (this.onReady) {
  16020. this.onReady(this);
  16021. }
  16022. this._isReady = true;
  16023. };
  16024. /**
  16025. * Get an animation by name
  16026. * @param name defines the name of the animation to look for
  16027. * @returns null if not found else the requested animation
  16028. */
  16029. Node.prototype.getAnimationByName = function (name) {
  16030. for (var i = 0; i < this.animations.length; i++) {
  16031. var animation = this.animations[i];
  16032. if (animation.name === name) {
  16033. return animation;
  16034. }
  16035. }
  16036. return null;
  16037. };
  16038. /**
  16039. * Creates an animation range for this node
  16040. * @param name defines the name of the range
  16041. * @param from defines the starting key
  16042. * @param to defines the end key
  16043. */
  16044. Node.prototype.createAnimationRange = function (name, from, to) {
  16045. // check name not already in use
  16046. if (!this._ranges[name]) {
  16047. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  16048. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16049. if (this.animations[i]) {
  16050. this.animations[i].createRange(name, from, to);
  16051. }
  16052. }
  16053. }
  16054. };
  16055. /**
  16056. * Delete a specific animation range
  16057. * @param name defines the name of the range to delete
  16058. * @param deleteFrames defines if animation frames from the range must be deleted as well
  16059. */
  16060. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  16061. if (deleteFrames === void 0) { deleteFrames = true; }
  16062. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16063. if (this.animations[i]) {
  16064. this.animations[i].deleteRange(name, deleteFrames);
  16065. }
  16066. }
  16067. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  16068. };
  16069. /**
  16070. * Get an animation range by name
  16071. * @param name defines the name of the animation range to look for
  16072. * @returns null if not found else the requested animation range
  16073. */
  16074. Node.prototype.getAnimationRange = function (name) {
  16075. return this._ranges[name];
  16076. };
  16077. /**
  16078. * Will start the animation sequence
  16079. * @param name defines the range frames for animation sequence
  16080. * @param loop defines if the animation should loop (false by default)
  16081. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  16082. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  16083. * @returns the object created for this animation. If range does not exist, it will return null
  16084. */
  16085. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  16086. var range = this.getAnimationRange(name);
  16087. if (!range) {
  16088. return null;
  16089. }
  16090. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  16091. };
  16092. /**
  16093. * Serialize animation ranges into a JSON compatible object
  16094. * @returns serialization object
  16095. */
  16096. Node.prototype.serializeAnimationRanges = function () {
  16097. var serializationRanges = [];
  16098. for (var name in this._ranges) {
  16099. var localRange = this._ranges[name];
  16100. if (!localRange) {
  16101. continue;
  16102. }
  16103. var range = {};
  16104. range.name = name;
  16105. range.from = localRange.from;
  16106. range.to = localRange.to;
  16107. serializationRanges.push(range);
  16108. }
  16109. return serializationRanges;
  16110. };
  16111. /**
  16112. * Computes the world matrix of the node
  16113. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  16114. * @returns the world matrix
  16115. */
  16116. Node.prototype.computeWorldMatrix = function (force) {
  16117. return BABYLON.Matrix.Identity();
  16118. };
  16119. /**
  16120. * Releases resources associated with this node.
  16121. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  16122. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  16123. */
  16124. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16125. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16126. if (!doNotRecurse) {
  16127. var nodes = this.getDescendants(true);
  16128. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  16129. var node = nodes_1[_i];
  16130. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  16131. }
  16132. }
  16133. else {
  16134. var transformNodes = this.getChildTransformNodes(true);
  16135. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  16136. var transformNode = transformNodes_1[_a];
  16137. transformNode.parent = null;
  16138. transformNode.computeWorldMatrix(true);
  16139. }
  16140. }
  16141. this.parent = null;
  16142. // Callback
  16143. this.onDisposeObservable.notifyObservers(this);
  16144. this.onDisposeObservable.clear();
  16145. // Behaviors
  16146. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  16147. var behavior = _c[_b];
  16148. behavior.detach();
  16149. }
  16150. this._behaviors = [];
  16151. this._isDisposed = true;
  16152. };
  16153. /**
  16154. * Parse animation range data from a serialization object and store them into a given node
  16155. * @param node defines where to store the animation ranges
  16156. * @param parsedNode defines the serialization object to read data from
  16157. * @param scene defines the hosting scene
  16158. */
  16159. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  16160. if (parsedNode.ranges) {
  16161. for (var index = 0; index < parsedNode.ranges.length; index++) {
  16162. var data = parsedNode.ranges[index];
  16163. node.createAnimationRange(data.name, data.from, data.to);
  16164. }
  16165. }
  16166. };
  16167. __decorate([
  16168. BABYLON.serialize()
  16169. ], Node.prototype, "name", void 0);
  16170. __decorate([
  16171. BABYLON.serialize()
  16172. ], Node.prototype, "id", void 0);
  16173. __decorate([
  16174. BABYLON.serialize()
  16175. ], Node.prototype, "uniqueId", void 0);
  16176. __decorate([
  16177. BABYLON.serialize()
  16178. ], Node.prototype, "state", void 0);
  16179. __decorate([
  16180. BABYLON.serialize()
  16181. ], Node.prototype, "metadata", void 0);
  16182. return Node;
  16183. }());
  16184. BABYLON.Node = Node;
  16185. })(BABYLON || (BABYLON = {}));
  16186. //# sourceMappingURL=babylon.node.js.map
  16187. "use strict";
  16188. var BABYLON;
  16189. (function (BABYLON) {
  16190. var BoundingSphere = /** @class */ (function () {
  16191. function BoundingSphere(minimum, maximum) {
  16192. this.minimum = minimum;
  16193. this.maximum = maximum;
  16194. this._tempRadiusVector = BABYLON.Vector3.Zero();
  16195. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  16196. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  16197. this.radius = distance * 0.5;
  16198. this.centerWorld = BABYLON.Vector3.Zero();
  16199. this._update(BABYLON.Matrix.Identity());
  16200. }
  16201. // Methods
  16202. BoundingSphere.prototype._update = function (world) {
  16203. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  16204. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  16205. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  16206. };
  16207. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  16208. for (var i = 0; i < 6; i++) {
  16209. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  16210. return false;
  16211. }
  16212. return true;
  16213. };
  16214. BoundingSphere.prototype.intersectsPoint = function (point) {
  16215. var x = this.centerWorld.x - point.x;
  16216. var y = this.centerWorld.y - point.y;
  16217. var z = this.centerWorld.z - point.z;
  16218. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16219. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  16220. return false;
  16221. return true;
  16222. };
  16223. // Statics
  16224. BoundingSphere.Intersects = function (sphere0, sphere1) {
  16225. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  16226. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  16227. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  16228. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16229. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  16230. return false;
  16231. return true;
  16232. };
  16233. return BoundingSphere;
  16234. }());
  16235. BABYLON.BoundingSphere = BoundingSphere;
  16236. })(BABYLON || (BABYLON = {}));
  16237. //# sourceMappingURL=babylon.boundingSphere.js.map
  16238. "use strict";
  16239. var BABYLON;
  16240. (function (BABYLON) {
  16241. var BoundingBox = /** @class */ (function () {
  16242. function BoundingBox(minimum, maximum) {
  16243. this.minimum = minimum;
  16244. this.maximum = maximum;
  16245. this.vectors = new Array();
  16246. this.vectorsWorld = new Array();
  16247. // Bounding vectors
  16248. this.vectors.push(this.minimum.clone());
  16249. this.vectors.push(this.maximum.clone());
  16250. this.vectors.push(this.minimum.clone());
  16251. this.vectors[2].x = this.maximum.x;
  16252. this.vectors.push(this.minimum.clone());
  16253. this.vectors[3].y = this.maximum.y;
  16254. this.vectors.push(this.minimum.clone());
  16255. this.vectors[4].z = this.maximum.z;
  16256. this.vectors.push(this.maximum.clone());
  16257. this.vectors[5].z = this.minimum.z;
  16258. this.vectors.push(this.maximum.clone());
  16259. this.vectors[6].x = this.minimum.x;
  16260. this.vectors.push(this.maximum.clone());
  16261. this.vectors[7].y = this.minimum.y;
  16262. // OBB
  16263. this.center = this.maximum.add(this.minimum).scale(0.5);
  16264. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  16265. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  16266. // World
  16267. for (var index = 0; index < this.vectors.length; index++) {
  16268. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  16269. }
  16270. this.minimumWorld = BABYLON.Vector3.Zero();
  16271. this.maximumWorld = BABYLON.Vector3.Zero();
  16272. this.centerWorld = BABYLON.Vector3.Zero();
  16273. this.extendSizeWorld = BABYLON.Vector3.Zero();
  16274. this._update(BABYLON.Matrix.Identity());
  16275. }
  16276. // Methods
  16277. BoundingBox.prototype.getWorldMatrix = function () {
  16278. return this._worldMatrix;
  16279. };
  16280. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  16281. this._worldMatrix.copyFrom(matrix);
  16282. return this;
  16283. };
  16284. BoundingBox.prototype._update = function (world) {
  16285. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  16286. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  16287. for (var index = 0; index < this.vectors.length; index++) {
  16288. var v = this.vectorsWorld[index];
  16289. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  16290. if (v.x < this.minimumWorld.x)
  16291. this.minimumWorld.x = v.x;
  16292. if (v.y < this.minimumWorld.y)
  16293. this.minimumWorld.y = v.y;
  16294. if (v.z < this.minimumWorld.z)
  16295. this.minimumWorld.z = v.z;
  16296. if (v.x > this.maximumWorld.x)
  16297. this.maximumWorld.x = v.x;
  16298. if (v.y > this.maximumWorld.y)
  16299. this.maximumWorld.y = v.y;
  16300. if (v.z > this.maximumWorld.z)
  16301. this.maximumWorld.z = v.z;
  16302. }
  16303. // Extend
  16304. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  16305. this.extendSizeWorld.scaleInPlace(0.5);
  16306. // OBB
  16307. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  16308. this.centerWorld.scaleInPlace(0.5);
  16309. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  16310. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  16311. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  16312. this._worldMatrix = world;
  16313. };
  16314. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  16315. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  16316. };
  16317. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16318. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16319. };
  16320. BoundingBox.prototype.intersectsPoint = function (point) {
  16321. var delta = -BABYLON.Epsilon;
  16322. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16323. return false;
  16324. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16325. return false;
  16326. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16327. return false;
  16328. return true;
  16329. };
  16330. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16331. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16332. };
  16333. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16334. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16335. return false;
  16336. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16337. return false;
  16338. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16339. return false;
  16340. return true;
  16341. };
  16342. // Statics
  16343. BoundingBox.Intersects = function (box0, box1) {
  16344. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16345. return false;
  16346. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16347. return false;
  16348. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16349. return false;
  16350. return true;
  16351. };
  16352. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16353. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16354. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16355. return (num <= (sphereRadius * sphereRadius));
  16356. };
  16357. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16358. for (var p = 0; p < 6; p++) {
  16359. for (var i = 0; i < 8; i++) {
  16360. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16361. return false;
  16362. }
  16363. }
  16364. }
  16365. return true;
  16366. };
  16367. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16368. for (var p = 0; p < 6; p++) {
  16369. var inCount = 8;
  16370. for (var i = 0; i < 8; i++) {
  16371. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16372. --inCount;
  16373. }
  16374. else {
  16375. break;
  16376. }
  16377. }
  16378. if (inCount === 0)
  16379. return false;
  16380. }
  16381. return true;
  16382. };
  16383. return BoundingBox;
  16384. }());
  16385. BABYLON.BoundingBox = BoundingBox;
  16386. })(BABYLON || (BABYLON = {}));
  16387. //# sourceMappingURL=babylon.boundingBox.js.map
  16388. "use strict";
  16389. var BABYLON;
  16390. (function (BABYLON) {
  16391. var computeBoxExtents = function (axis, box) {
  16392. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16393. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16394. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16395. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16396. var r = r0 + r1 + r2;
  16397. return {
  16398. min: p - r,
  16399. max: p + r
  16400. };
  16401. };
  16402. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16403. var axisOverlap = function (axis, box0, box1) {
  16404. var result0 = computeBoxExtents(axis, box0);
  16405. var result1 = computeBoxExtents(axis, box1);
  16406. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16407. };
  16408. var BoundingInfo = /** @class */ (function () {
  16409. function BoundingInfo(minimum, maximum) {
  16410. this.minimum = minimum;
  16411. this.maximum = maximum;
  16412. this._isLocked = false;
  16413. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16414. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16415. }
  16416. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16417. get: function () {
  16418. return this._isLocked;
  16419. },
  16420. set: function (value) {
  16421. this._isLocked = value;
  16422. },
  16423. enumerable: true,
  16424. configurable: true
  16425. });
  16426. // Methods
  16427. BoundingInfo.prototype.update = function (world) {
  16428. if (this._isLocked) {
  16429. return;
  16430. }
  16431. this.boundingBox._update(world);
  16432. this.boundingSphere._update(world);
  16433. };
  16434. /**
  16435. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16436. * @param center New center of the bounding info
  16437. * @param extend New extend of the bounding info
  16438. */
  16439. BoundingInfo.prototype.centerOn = function (center, extend) {
  16440. this.minimum = center.subtract(extend);
  16441. this.maximum = center.add(extend);
  16442. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16443. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16444. return this;
  16445. };
  16446. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16447. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16448. return false;
  16449. return this.boundingBox.isInFrustum(frustumPlanes);
  16450. };
  16451. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16452. /**
  16453. * Gets the world distance between the min and max points of the bounding box
  16454. */
  16455. get: function () {
  16456. var boundingBox = this.boundingBox;
  16457. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16458. return size.length();
  16459. },
  16460. enumerable: true,
  16461. configurable: true
  16462. });
  16463. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16464. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16465. };
  16466. BoundingInfo.prototype._checkCollision = function (collider) {
  16467. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16468. };
  16469. BoundingInfo.prototype.intersectsPoint = function (point) {
  16470. if (!this.boundingSphere.centerWorld) {
  16471. return false;
  16472. }
  16473. if (!this.boundingSphere.intersectsPoint(point)) {
  16474. return false;
  16475. }
  16476. if (!this.boundingBox.intersectsPoint(point)) {
  16477. return false;
  16478. }
  16479. return true;
  16480. };
  16481. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16482. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16483. return false;
  16484. }
  16485. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16486. return false;
  16487. }
  16488. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16489. return false;
  16490. }
  16491. if (!precise) {
  16492. return true;
  16493. }
  16494. var box0 = this.boundingBox;
  16495. var box1 = boundingInfo.boundingBox;
  16496. if (!axisOverlap(box0.directions[0], box0, box1))
  16497. return false;
  16498. if (!axisOverlap(box0.directions[1], box0, box1))
  16499. return false;
  16500. if (!axisOverlap(box0.directions[2], box0, box1))
  16501. return false;
  16502. if (!axisOverlap(box1.directions[0], box0, box1))
  16503. return false;
  16504. if (!axisOverlap(box1.directions[1], box0, box1))
  16505. return false;
  16506. if (!axisOverlap(box1.directions[2], box0, box1))
  16507. return false;
  16508. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16509. return false;
  16510. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16511. return false;
  16512. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16513. return false;
  16514. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16515. return false;
  16516. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16517. return false;
  16518. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16519. return false;
  16520. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16521. return false;
  16522. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16523. return false;
  16524. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16525. return false;
  16526. return true;
  16527. };
  16528. return BoundingInfo;
  16529. }());
  16530. BABYLON.BoundingInfo = BoundingInfo;
  16531. })(BABYLON || (BABYLON = {}));
  16532. //# sourceMappingURL=babylon.boundingInfo.js.map
  16533. "use strict";
  16534. var BABYLON;
  16535. (function (BABYLON) {
  16536. var TransformNode = /** @class */ (function (_super) {
  16537. __extends(TransformNode, _super);
  16538. function TransformNode(name, scene, isPure) {
  16539. if (scene === void 0) { scene = null; }
  16540. if (isPure === void 0) { isPure = true; }
  16541. var _this = _super.call(this, name, scene) || this;
  16542. // Properties
  16543. _this._rotation = BABYLON.Vector3.Zero();
  16544. _this._scaling = BABYLON.Vector3.One();
  16545. _this._isDirty = false;
  16546. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  16547. _this.scalingDeterminant = 1;
  16548. _this.infiniteDistance = false;
  16549. _this.position = BABYLON.Vector3.Zero();
  16550. _this._localWorld = BABYLON.Matrix.Zero();
  16551. _this._worldMatrix = BABYLON.Matrix.Zero();
  16552. _this._worldMatrixDeterminant = 0;
  16553. _this._absolutePosition = BABYLON.Vector3.Zero();
  16554. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16555. _this._postMultiplyPivotMatrix = false;
  16556. _this._isWorldMatrixFrozen = false;
  16557. /**
  16558. * An event triggered after the world matrix is updated
  16559. * @type {BABYLON.Observable}
  16560. */
  16561. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16562. _this._nonUniformScaling = false;
  16563. if (isPure) {
  16564. _this.getScene().addTransformNode(_this);
  16565. }
  16566. return _this;
  16567. }
  16568. /**
  16569. * Gets a string idenfifying the name of the class
  16570. * @returns "TransformNode" string
  16571. */
  16572. TransformNode.prototype.getClassName = function () {
  16573. return "TransformNode";
  16574. };
  16575. Object.defineProperty(TransformNode.prototype, "rotation", {
  16576. /**
  16577. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16578. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16579. * Default : (0.0, 0.0, 0.0)
  16580. */
  16581. get: function () {
  16582. return this._rotation;
  16583. },
  16584. set: function (newRotation) {
  16585. this._rotation = newRotation;
  16586. },
  16587. enumerable: true,
  16588. configurable: true
  16589. });
  16590. Object.defineProperty(TransformNode.prototype, "scaling", {
  16591. /**
  16592. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16593. * Default : (1.0, 1.0, 1.0)
  16594. */
  16595. get: function () {
  16596. return this._scaling;
  16597. },
  16598. /**
  16599. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16600. * Default : (1.0, 1.0, 1.0)
  16601. */
  16602. set: function (newScaling) {
  16603. this._scaling = newScaling;
  16604. },
  16605. enumerable: true,
  16606. configurable: true
  16607. });
  16608. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16609. /**
  16610. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16611. * It's null by default.
  16612. * 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)
  16613. */
  16614. get: function () {
  16615. return this._rotationQuaternion;
  16616. },
  16617. set: function (quaternion) {
  16618. this._rotationQuaternion = quaternion;
  16619. //reset the rotation vector.
  16620. if (quaternion && this.rotation.length()) {
  16621. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16622. }
  16623. },
  16624. enumerable: true,
  16625. configurable: true
  16626. });
  16627. /**
  16628. * Returns the latest update of the World matrix
  16629. * Returns a Matrix.
  16630. */
  16631. TransformNode.prototype.getWorldMatrix = function () {
  16632. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16633. this.computeWorldMatrix();
  16634. }
  16635. return this._worldMatrix;
  16636. };
  16637. /**
  16638. * Returns the latest update of the World matrix determinant.
  16639. */
  16640. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16641. return this._worldMatrixDeterminant;
  16642. };
  16643. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16644. /**
  16645. * Returns directly the latest state of the mesh World matrix.
  16646. * A Matrix is returned.
  16647. */
  16648. get: function () {
  16649. return this._worldMatrix;
  16650. },
  16651. enumerable: true,
  16652. configurable: true
  16653. });
  16654. /**
  16655. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16656. * Returns the AbstractMesh.
  16657. */
  16658. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16659. this._poseMatrix.copyFrom(matrix);
  16660. return this;
  16661. };
  16662. /**
  16663. * Returns the mesh Pose matrix.
  16664. * Returned object : Matrix
  16665. */
  16666. TransformNode.prototype.getPoseMatrix = function () {
  16667. return this._poseMatrix;
  16668. };
  16669. TransformNode.prototype._isSynchronized = function () {
  16670. if (this._isDirty) {
  16671. return false;
  16672. }
  16673. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16674. return false;
  16675. if (this._cache.pivotMatrixUpdated) {
  16676. return false;
  16677. }
  16678. if (this.infiniteDistance) {
  16679. return false;
  16680. }
  16681. if (!this._cache.position.equals(this.position))
  16682. return false;
  16683. if (this.rotationQuaternion) {
  16684. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16685. return false;
  16686. }
  16687. if (!this._cache.rotation.equals(this.rotation))
  16688. return false;
  16689. if (!this._cache.scaling.equals(this.scaling))
  16690. return false;
  16691. return true;
  16692. };
  16693. TransformNode.prototype._initCache = function () {
  16694. _super.prototype._initCache.call(this);
  16695. this._cache.localMatrixUpdated = false;
  16696. this._cache.position = BABYLON.Vector3.Zero();
  16697. this._cache.scaling = BABYLON.Vector3.Zero();
  16698. this._cache.rotation = BABYLON.Vector3.Zero();
  16699. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16700. this._cache.billboardMode = -1;
  16701. };
  16702. TransformNode.prototype.markAsDirty = function (property) {
  16703. if (property === "rotation") {
  16704. this.rotationQuaternion = null;
  16705. }
  16706. this._currentRenderId = Number.MAX_VALUE;
  16707. this._isDirty = true;
  16708. return this;
  16709. };
  16710. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16711. /**
  16712. * Returns the current mesh absolute position.
  16713. * Retuns a Vector3.
  16714. */
  16715. get: function () {
  16716. return this._absolutePosition;
  16717. },
  16718. enumerable: true,
  16719. configurable: true
  16720. });
  16721. /**
  16722. * Sets a new matrix to apply before all other transformation
  16723. * @param matrix defines the transform matrix
  16724. * @returns the current TransformNode
  16725. */
  16726. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16727. return this.setPivotMatrix(matrix, false);
  16728. };
  16729. /**
  16730. * Sets a new pivot matrix to the current node
  16731. * @param matrix defines the new pivot matrix to use
  16732. * @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
  16733. * @returns the current TransformNode
  16734. */
  16735. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16736. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16737. this._pivotMatrix = matrix.clone();
  16738. this._cache.pivotMatrixUpdated = true;
  16739. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16740. if (this._postMultiplyPivotMatrix) {
  16741. if (!this._pivotMatrixInverse) {
  16742. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16743. }
  16744. else {
  16745. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16746. }
  16747. }
  16748. return this;
  16749. };
  16750. /**
  16751. * Returns the mesh pivot matrix.
  16752. * Default : Identity.
  16753. * A Matrix is returned.
  16754. */
  16755. TransformNode.prototype.getPivotMatrix = function () {
  16756. return this._pivotMatrix;
  16757. };
  16758. /**
  16759. * Prevents the World matrix to be computed any longer.
  16760. * Returns the AbstractMesh.
  16761. */
  16762. TransformNode.prototype.freezeWorldMatrix = function () {
  16763. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16764. this.computeWorldMatrix(true);
  16765. this._isWorldMatrixFrozen = true;
  16766. return this;
  16767. };
  16768. /**
  16769. * Allows back the World matrix computation.
  16770. * Returns the AbstractMesh.
  16771. */
  16772. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16773. this._isWorldMatrixFrozen = false;
  16774. this.computeWorldMatrix(true);
  16775. return this;
  16776. };
  16777. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16778. /**
  16779. * True if the World matrix has been frozen.
  16780. * Returns a boolean.
  16781. */
  16782. get: function () {
  16783. return this._isWorldMatrixFrozen;
  16784. },
  16785. enumerable: true,
  16786. configurable: true
  16787. });
  16788. /**
  16789. * Retuns the mesh absolute position in the World.
  16790. * Returns a Vector3.
  16791. */
  16792. TransformNode.prototype.getAbsolutePosition = function () {
  16793. this.computeWorldMatrix();
  16794. return this._absolutePosition;
  16795. };
  16796. /**
  16797. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16798. * Returns the AbstractMesh.
  16799. */
  16800. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16801. if (!absolutePosition) {
  16802. return this;
  16803. }
  16804. var absolutePositionX;
  16805. var absolutePositionY;
  16806. var absolutePositionZ;
  16807. if (absolutePosition.x === undefined) {
  16808. if (arguments.length < 3) {
  16809. return this;
  16810. }
  16811. absolutePositionX = arguments[0];
  16812. absolutePositionY = arguments[1];
  16813. absolutePositionZ = arguments[2];
  16814. }
  16815. else {
  16816. absolutePositionX = absolutePosition.x;
  16817. absolutePositionY = absolutePosition.y;
  16818. absolutePositionZ = absolutePosition.z;
  16819. }
  16820. if (this.parent) {
  16821. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16822. invertParentWorldMatrix.invert();
  16823. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16824. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16825. }
  16826. else {
  16827. this.position.x = absolutePositionX;
  16828. this.position.y = absolutePositionY;
  16829. this.position.z = absolutePositionZ;
  16830. }
  16831. return this;
  16832. };
  16833. /**
  16834. * Sets the mesh position in its local space.
  16835. * Returns the AbstractMesh.
  16836. */
  16837. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16838. this.computeWorldMatrix();
  16839. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16840. return this;
  16841. };
  16842. /**
  16843. * Returns the mesh position in the local space from the current World matrix values.
  16844. * Returns a new Vector3.
  16845. */
  16846. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16847. this.computeWorldMatrix();
  16848. var invLocalWorldMatrix = this._localWorld.clone();
  16849. invLocalWorldMatrix.invert();
  16850. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16851. };
  16852. /**
  16853. * Translates the mesh along the passed Vector3 in its local space.
  16854. * Returns the AbstractMesh.
  16855. */
  16856. TransformNode.prototype.locallyTranslate = function (vector3) {
  16857. this.computeWorldMatrix(true);
  16858. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16859. return this;
  16860. };
  16861. /**
  16862. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16863. * @param targetPoint the position (must be in same space as current mesh) to look at
  16864. * @param yawCor optional yaw (y-axis) correction in radians
  16865. * @param pitchCor optional pitch (x-axis) correction in radians
  16866. * @param rollCor optional roll (z-axis) correction in radians
  16867. * @param space the choosen space of the target
  16868. * @returns the TransformNode.
  16869. */
  16870. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16871. if (yawCor === void 0) { yawCor = 0; }
  16872. if (pitchCor === void 0) { pitchCor = 0; }
  16873. if (rollCor === void 0) { rollCor = 0; }
  16874. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16875. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16876. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16877. targetPoint.subtractToRef(pos, dv);
  16878. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16879. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16880. var pitch = Math.atan2(dv.y, len);
  16881. if (this.rotationQuaternion) {
  16882. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16883. }
  16884. else {
  16885. this.rotation.x = pitch + pitchCor;
  16886. this.rotation.y = yaw + yawCor;
  16887. this.rotation.z = rollCor;
  16888. }
  16889. return this;
  16890. };
  16891. /**
  16892. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16893. * This Vector3 is expressed in the World space.
  16894. */
  16895. TransformNode.prototype.getDirection = function (localAxis) {
  16896. var result = BABYLON.Vector3.Zero();
  16897. this.getDirectionToRef(localAxis, result);
  16898. return result;
  16899. };
  16900. /**
  16901. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16902. * localAxis is expressed in the mesh local space.
  16903. * result is computed in the Wordl space from the mesh World matrix.
  16904. * Returns the AbstractMesh.
  16905. */
  16906. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16907. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16908. return this;
  16909. };
  16910. /**
  16911. * Sets a new pivot point to the current node
  16912. * @param point defines the new pivot point to use
  16913. * @param space defines if the point is in world or local space (local by default)
  16914. * @returns the current TransformNode
  16915. */
  16916. TransformNode.prototype.setPivotPoint = function (point, space) {
  16917. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16918. if (this.getScene().getRenderId() == 0) {
  16919. this.computeWorldMatrix(true);
  16920. }
  16921. var wm = this.getWorldMatrix();
  16922. if (space == BABYLON.Space.WORLD) {
  16923. var tmat = BABYLON.Tmp.Matrix[0];
  16924. wm.invertToRef(tmat);
  16925. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16926. }
  16927. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16928. };
  16929. /**
  16930. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16931. */
  16932. TransformNode.prototype.getPivotPoint = function () {
  16933. var point = BABYLON.Vector3.Zero();
  16934. this.getPivotPointToRef(point);
  16935. return point;
  16936. };
  16937. /**
  16938. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16939. * Returns the AbstractMesh.
  16940. */
  16941. TransformNode.prototype.getPivotPointToRef = function (result) {
  16942. result.x = -this._pivotMatrix.m[12];
  16943. result.y = -this._pivotMatrix.m[13];
  16944. result.z = -this._pivotMatrix.m[14];
  16945. return this;
  16946. };
  16947. /**
  16948. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16949. */
  16950. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16951. var point = BABYLON.Vector3.Zero();
  16952. this.getAbsolutePivotPointToRef(point);
  16953. return point;
  16954. };
  16955. /**
  16956. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16957. * Returns the AbstractMesh.
  16958. */
  16959. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16960. result.x = this._pivotMatrix.m[12];
  16961. result.y = this._pivotMatrix.m[13];
  16962. result.z = this._pivotMatrix.m[14];
  16963. this.getPivotPointToRef(result);
  16964. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16965. return this;
  16966. };
  16967. /**
  16968. * Defines the passed node as the parent of the current node.
  16969. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16970. * Returns the TransformNode.
  16971. */
  16972. TransformNode.prototype.setParent = function (node) {
  16973. if (node === null) {
  16974. var rotation = BABYLON.Tmp.Quaternion[0];
  16975. var position = BABYLON.Tmp.Vector3[0];
  16976. var scale = BABYLON.Tmp.Vector3[1];
  16977. if (this.parent && this.parent.computeWorldMatrix) {
  16978. this.parent.computeWorldMatrix(true);
  16979. }
  16980. this.computeWorldMatrix(true);
  16981. this.getWorldMatrix().decompose(scale, rotation, position);
  16982. if (this.rotationQuaternion) {
  16983. this.rotationQuaternion.copyFrom(rotation);
  16984. }
  16985. else {
  16986. rotation.toEulerAnglesToRef(this.rotation);
  16987. }
  16988. this.scaling.x = scale.x;
  16989. this.scaling.y = scale.y;
  16990. this.scaling.z = scale.z;
  16991. this.position.x = position.x;
  16992. this.position.y = position.y;
  16993. this.position.z = position.z;
  16994. }
  16995. else {
  16996. var rotation = BABYLON.Tmp.Quaternion[0];
  16997. var position = BABYLON.Tmp.Vector3[0];
  16998. var scale = BABYLON.Tmp.Vector3[1];
  16999. var diffMatrix = BABYLON.Tmp.Matrix[0];
  17000. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  17001. this.computeWorldMatrix(true);
  17002. node.computeWorldMatrix(true);
  17003. node.getWorldMatrix().invertToRef(invParentMatrix);
  17004. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  17005. diffMatrix.decompose(scale, rotation, position);
  17006. if (this.rotationQuaternion) {
  17007. this.rotationQuaternion.copyFrom(rotation);
  17008. }
  17009. else {
  17010. rotation.toEulerAnglesToRef(this.rotation);
  17011. }
  17012. this.position.x = position.x;
  17013. this.position.y = position.y;
  17014. this.position.z = position.z;
  17015. this.scaling.x = scale.x;
  17016. this.scaling.y = scale.y;
  17017. this.scaling.z = scale.z;
  17018. }
  17019. this.parent = node;
  17020. return this;
  17021. };
  17022. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  17023. get: function () {
  17024. return this._nonUniformScaling;
  17025. },
  17026. enumerable: true,
  17027. configurable: true
  17028. });
  17029. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  17030. if (this._nonUniformScaling === value) {
  17031. return false;
  17032. }
  17033. this._nonUniformScaling = true;
  17034. return true;
  17035. };
  17036. /**
  17037. * Attach the current TransformNode to another TransformNode associated with a bone
  17038. * @param bone Bone affecting the TransformNode
  17039. * @param affectedTransformNode TransformNode associated with the bone
  17040. */
  17041. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  17042. this._transformToBoneReferal = affectedTransformNode;
  17043. this.parent = bone;
  17044. if (bone.getWorldMatrix().determinant() < 0) {
  17045. this.scalingDeterminant *= -1;
  17046. }
  17047. return this;
  17048. };
  17049. TransformNode.prototype.detachFromBone = function () {
  17050. if (!this.parent) {
  17051. return this;
  17052. }
  17053. if (this.parent.getWorldMatrix().determinant() < 0) {
  17054. this.scalingDeterminant *= -1;
  17055. }
  17056. this._transformToBoneReferal = null;
  17057. this.parent = null;
  17058. return this;
  17059. };
  17060. /**
  17061. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  17062. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17063. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17064. * The passed axis is also normalized.
  17065. * Returns the AbstractMesh.
  17066. */
  17067. TransformNode.prototype.rotate = function (axis, amount, space) {
  17068. axis.normalize();
  17069. if (!this.rotationQuaternion) {
  17070. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17071. this.rotation = BABYLON.Vector3.Zero();
  17072. }
  17073. var rotationQuaternion;
  17074. if (!space || space === BABYLON.Space.LOCAL) {
  17075. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  17076. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  17077. }
  17078. else {
  17079. if (this.parent) {
  17080. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  17081. invertParentWorldMatrix.invert();
  17082. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  17083. }
  17084. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  17085. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17086. }
  17087. return this;
  17088. };
  17089. /**
  17090. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  17091. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17092. * The passed axis is also normalized.
  17093. * Returns the AbstractMesh.
  17094. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  17095. */
  17096. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  17097. axis.normalize();
  17098. if (!this.rotationQuaternion) {
  17099. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17100. this.rotation.copyFromFloats(0, 0, 0);
  17101. }
  17102. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  17103. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  17104. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  17105. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  17106. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  17107. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  17108. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  17109. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  17110. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17111. return this;
  17112. };
  17113. /**
  17114. * Translates the mesh along the axis vector for the passed distance in the given space.
  17115. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17116. * Returns the AbstractMesh.
  17117. */
  17118. TransformNode.prototype.translate = function (axis, distance, space) {
  17119. var displacementVector = axis.scale(distance);
  17120. if (!space || space === BABYLON.Space.LOCAL) {
  17121. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  17122. this.setPositionWithLocalVector(tempV3);
  17123. }
  17124. else {
  17125. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  17126. }
  17127. return this;
  17128. };
  17129. /**
  17130. * Adds a rotation step to the mesh current rotation.
  17131. * x, y, z are Euler angles expressed in radians.
  17132. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  17133. * This means this rotation is made in the mesh local space only.
  17134. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  17135. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  17136. * ```javascript
  17137. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  17138. * ```
  17139. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  17140. * 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.
  17141. * Returns the AbstractMesh.
  17142. */
  17143. TransformNode.prototype.addRotation = function (x, y, z) {
  17144. var rotationQuaternion;
  17145. if (this.rotationQuaternion) {
  17146. rotationQuaternion = this.rotationQuaternion;
  17147. }
  17148. else {
  17149. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  17150. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  17151. }
  17152. var accumulation = BABYLON.Tmp.Quaternion[0];
  17153. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  17154. rotationQuaternion.multiplyInPlace(accumulation);
  17155. if (!this.rotationQuaternion) {
  17156. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  17157. }
  17158. return this;
  17159. };
  17160. /**
  17161. * Computes the mesh World matrix and returns it.
  17162. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  17163. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  17164. * If the parameter `force`is set to `true`, the actual computation is done.
  17165. * Returns the mesh World Matrix.
  17166. */
  17167. TransformNode.prototype.computeWorldMatrix = function (force) {
  17168. if (this._isWorldMatrixFrozen) {
  17169. return this._worldMatrix;
  17170. }
  17171. if (!force && this.isSynchronized(true)) {
  17172. return this._worldMatrix;
  17173. }
  17174. this._cache.position.copyFrom(this.position);
  17175. this._cache.scaling.copyFrom(this.scaling);
  17176. this._cache.pivotMatrixUpdated = false;
  17177. this._cache.billboardMode = this.billboardMode;
  17178. this._currentRenderId = this.getScene().getRenderId();
  17179. this._isDirty = false;
  17180. // Scaling
  17181. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  17182. // Rotation
  17183. //rotate, if quaternion is set and rotation was used
  17184. if (this.rotationQuaternion) {
  17185. var len = this.rotation.length();
  17186. if (len) {
  17187. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  17188. this.rotation.copyFromFloats(0, 0, 0);
  17189. }
  17190. }
  17191. if (this.rotationQuaternion) {
  17192. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  17193. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17194. }
  17195. else {
  17196. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  17197. this._cache.rotation.copyFrom(this.rotation);
  17198. }
  17199. // Translation
  17200. var camera = this.getScene().activeCamera;
  17201. if (this.infiniteDistance && !this.parent && camera) {
  17202. var cameraWorldMatrix = camera.getWorldMatrix();
  17203. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  17204. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  17205. }
  17206. else {
  17207. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  17208. }
  17209. // Composing transformations
  17210. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  17211. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17212. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  17213. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  17214. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  17215. // Need to decompose each rotation here
  17216. var currentPosition = BABYLON.Tmp.Vector3[3];
  17217. if (this.parent && this.parent.getWorldMatrix) {
  17218. if (this._transformToBoneReferal) {
  17219. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17220. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  17221. }
  17222. else {
  17223. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  17224. }
  17225. }
  17226. else {
  17227. currentPosition.copyFrom(this.position);
  17228. }
  17229. currentPosition.subtractInPlace(camera.globalPosition);
  17230. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  17231. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  17232. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  17233. }
  17234. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  17235. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  17236. }
  17237. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  17238. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  17239. }
  17240. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  17241. }
  17242. else {
  17243. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  17244. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  17245. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  17246. }
  17247. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  17248. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17249. }
  17250. // Local world
  17251. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  17252. // Parent
  17253. if (this.parent && this.parent.getWorldMatrix) {
  17254. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  17255. if (this._transformToBoneReferal) {
  17256. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17257. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  17258. }
  17259. else {
  17260. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  17261. }
  17262. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  17263. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  17264. this._worldMatrix.copyFrom(this._localWorld);
  17265. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  17266. }
  17267. else {
  17268. if (this._transformToBoneReferal) {
  17269. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17270. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  17271. }
  17272. else {
  17273. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  17274. }
  17275. }
  17276. this._markSyncedWithParent();
  17277. }
  17278. else {
  17279. this._worldMatrix.copyFrom(this._localWorld);
  17280. }
  17281. // Post multiply inverse of pivotMatrix
  17282. if (this._postMultiplyPivotMatrix) {
  17283. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  17284. }
  17285. // Normal matrix
  17286. if (this.scaling.isNonUniform) {
  17287. this._updateNonUniformScalingState(true);
  17288. }
  17289. else if (this.parent && this.parent._nonUniformScaling) {
  17290. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  17291. }
  17292. else {
  17293. this._updateNonUniformScalingState(false);
  17294. }
  17295. this._afterComputeWorldMatrix();
  17296. // Absolute position
  17297. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  17298. // Callbacks
  17299. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  17300. if (!this._poseMatrix) {
  17301. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  17302. }
  17303. // Cache the determinant
  17304. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  17305. return this._worldMatrix;
  17306. };
  17307. TransformNode.prototype._afterComputeWorldMatrix = function () {
  17308. };
  17309. /**
  17310. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  17311. * @param func: callback function to add
  17312. *
  17313. * Returns the TransformNode.
  17314. */
  17315. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  17316. this.onAfterWorldMatrixUpdateObservable.add(func);
  17317. return this;
  17318. };
  17319. /**
  17320. * Removes a registered callback function.
  17321. * Returns the TransformNode.
  17322. */
  17323. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  17324. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  17325. return this;
  17326. };
  17327. /**
  17328. * Clone the current transform node
  17329. * Returns the new transform node
  17330. * @param name Name of the new clone
  17331. * @param newParent New parent for the clone
  17332. * @param doNotCloneChildren Do not clone children hierarchy
  17333. */
  17334. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17335. var _this = this;
  17336. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17337. result.name = name;
  17338. result.id = name;
  17339. if (newParent) {
  17340. result.parent = newParent;
  17341. }
  17342. if (!doNotCloneChildren) {
  17343. // Children
  17344. var directDescendants = this.getDescendants(true);
  17345. for (var index = 0; index < directDescendants.length; index++) {
  17346. var child = directDescendants[index];
  17347. if (child.clone) {
  17348. child.clone(name + "." + child.name, result);
  17349. }
  17350. }
  17351. }
  17352. return result;
  17353. };
  17354. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17355. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17356. serializationObject.type = this.getClassName();
  17357. // Parent
  17358. if (this.parent) {
  17359. serializationObject.parentId = this.parent.id;
  17360. }
  17361. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17362. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17363. }
  17364. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17365. serializationObject.isEnabled = this.isEnabled();
  17366. // Parent
  17367. if (this.parent) {
  17368. serializationObject.parentId = this.parent.id;
  17369. }
  17370. return serializationObject;
  17371. };
  17372. // Statics
  17373. /**
  17374. * Returns a new TransformNode object parsed from the source provided.
  17375. * The parameter `parsedMesh` is the source.
  17376. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17377. */
  17378. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17379. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17380. if (BABYLON.Tags) {
  17381. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17382. }
  17383. if (parsedTransformNode.localMatrix) {
  17384. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17385. }
  17386. else if (parsedTransformNode.pivotMatrix) {
  17387. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17388. }
  17389. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17390. // Parent
  17391. if (parsedTransformNode.parentId) {
  17392. transformNode._waitingParentId = parsedTransformNode.parentId;
  17393. }
  17394. return transformNode;
  17395. };
  17396. /**
  17397. * Releases resources associated with this transform node.
  17398. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17399. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17400. */
  17401. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17402. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17403. // Animations
  17404. this.getScene().stopAnimation(this);
  17405. // Remove from scene
  17406. this.getScene().removeTransformNode(this);
  17407. this.onAfterWorldMatrixUpdateObservable.clear();
  17408. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  17409. };
  17410. // Statics
  17411. TransformNode.BILLBOARDMODE_NONE = 0;
  17412. TransformNode.BILLBOARDMODE_X = 1;
  17413. TransformNode.BILLBOARDMODE_Y = 2;
  17414. TransformNode.BILLBOARDMODE_Z = 4;
  17415. TransformNode.BILLBOARDMODE_ALL = 7;
  17416. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17417. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17418. __decorate([
  17419. BABYLON.serializeAsVector3()
  17420. ], TransformNode.prototype, "_rotation", void 0);
  17421. __decorate([
  17422. BABYLON.serializeAsQuaternion()
  17423. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17424. __decorate([
  17425. BABYLON.serializeAsVector3()
  17426. ], TransformNode.prototype, "_scaling", void 0);
  17427. __decorate([
  17428. BABYLON.serialize()
  17429. ], TransformNode.prototype, "billboardMode", void 0);
  17430. __decorate([
  17431. BABYLON.serialize()
  17432. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17433. __decorate([
  17434. BABYLON.serialize()
  17435. ], TransformNode.prototype, "infiniteDistance", void 0);
  17436. __decorate([
  17437. BABYLON.serializeAsVector3()
  17438. ], TransformNode.prototype, "position", void 0);
  17439. return TransformNode;
  17440. }(BABYLON.Node));
  17441. BABYLON.TransformNode = TransformNode;
  17442. })(BABYLON || (BABYLON = {}));
  17443. //# sourceMappingURL=babylon.transformNode.js.map
  17444. "use strict";
  17445. var BABYLON;
  17446. (function (BABYLON) {
  17447. var AbstractMesh = /** @class */ (function (_super) {
  17448. __extends(AbstractMesh, _super);
  17449. // Constructor
  17450. function AbstractMesh(name, scene) {
  17451. if (scene === void 0) { scene = null; }
  17452. var _this = _super.call(this, name, scene, false) || this;
  17453. _this._facetNb = 0; // facet number
  17454. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17455. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17456. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17457. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17458. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17459. _this._subDiv = {
  17460. max: 1,
  17461. X: 1,
  17462. Y: 1,
  17463. Z: 1
  17464. };
  17465. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17466. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17467. // Events
  17468. /**
  17469. * An event triggered when this mesh collides with another one
  17470. * @type {BABYLON.Observable}
  17471. */
  17472. _this.onCollideObservable = new BABYLON.Observable();
  17473. /**
  17474. * An event triggered when the collision's position changes
  17475. * @type {BABYLON.Observable}
  17476. */
  17477. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17478. /**
  17479. * An event triggered when material is changed
  17480. * @type {BABYLON.Observable}
  17481. */
  17482. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17483. // Properties
  17484. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17485. /**
  17486. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17487. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17488. * or
  17489. * 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.
  17490. * for more info check WebGl documentations
  17491. */
  17492. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17493. /**
  17494. * 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:
  17495. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17496. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17497. * 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.
  17498. */
  17499. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17500. /**
  17501. * 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.
  17502. * The default value is -1 which means don't break the query and wait till the result.
  17503. */
  17504. _this.occlusionRetryCount = -1;
  17505. _this._occlusionInternalRetryCounter = 0;
  17506. _this._isOccluded = false;
  17507. _this._isOcclusionQueryInProgress = false;
  17508. _this._visibility = 1.0;
  17509. _this.alphaIndex = Number.MAX_VALUE;
  17510. _this.isVisible = true;
  17511. _this.isPickable = true;
  17512. _this.showBoundingBox = false;
  17513. _this.showSubMeshesBoundingBox = false;
  17514. _this.isBlocker = false;
  17515. _this.enablePointerMoveEvents = false;
  17516. _this.renderingGroupId = 0;
  17517. _this._receiveShadows = false;
  17518. _this.renderOutline = false;
  17519. _this.outlineColor = BABYLON.Color3.Red();
  17520. _this.outlineWidth = 0.02;
  17521. _this.renderOverlay = false;
  17522. _this.overlayColor = BABYLON.Color3.Red();
  17523. _this.overlayAlpha = 0.5;
  17524. _this._hasVertexAlpha = false;
  17525. _this._useVertexColors = true;
  17526. _this._computeBonesUsingShaders = true;
  17527. _this._numBoneInfluencers = 4;
  17528. _this._applyFog = true;
  17529. _this.useOctreeForRenderingSelection = true;
  17530. _this.useOctreeForPicking = true;
  17531. _this.useOctreeForCollisions = true;
  17532. _this._layerMask = 0x0FFFFFFF;
  17533. /**
  17534. * True if the mesh must be rendered in any case.
  17535. */
  17536. _this.alwaysSelectAsActiveMesh = false;
  17537. /**
  17538. * This scene's action manager
  17539. * @type {BABYLON.ActionManager}
  17540. */
  17541. _this.actionManager = null;
  17542. // Physics
  17543. _this.physicsImpostor = null;
  17544. // Collisions
  17545. _this._checkCollisions = false;
  17546. _this._collisionMask = -1;
  17547. _this._collisionGroup = -1;
  17548. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17549. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17550. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17551. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17552. // Edges
  17553. _this.edgesWidth = 1;
  17554. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17555. // Cache
  17556. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17557. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17558. _this._renderId = 0;
  17559. _this._intersectionsInProgress = new Array();
  17560. _this._unIndexed = false;
  17561. _this._lightSources = new Array();
  17562. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17563. if (collidedMesh === void 0) { collidedMesh = null; }
  17564. //TODO move this to the collision coordinator!
  17565. if (_this.getScene().workerCollisions)
  17566. newPosition.multiplyInPlace(_this._collider._radius);
  17567. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17568. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17569. _this.position.addInPlace(_this._diffPositionForCollisions);
  17570. }
  17571. if (collidedMesh) {
  17572. _this.onCollideObservable.notifyObservers(collidedMesh);
  17573. }
  17574. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17575. };
  17576. _this.getScene().addMesh(_this);
  17577. _this._resyncLightSources();
  17578. return _this;
  17579. }
  17580. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17581. get: function () {
  17582. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17583. },
  17584. enumerable: true,
  17585. configurable: true
  17586. });
  17587. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17588. get: function () {
  17589. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17590. },
  17591. enumerable: true,
  17592. configurable: true
  17593. });
  17594. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17595. get: function () {
  17596. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17597. },
  17598. enumerable: true,
  17599. configurable: true
  17600. });
  17601. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17602. get: function () {
  17603. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17604. },
  17605. enumerable: true,
  17606. configurable: true
  17607. });
  17608. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17609. get: function () {
  17610. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17611. },
  17612. enumerable: true,
  17613. configurable: true
  17614. });
  17615. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17616. /**
  17617. * Read-only : the number of facets in the mesh
  17618. */
  17619. get: function () {
  17620. return this._facetNb;
  17621. },
  17622. enumerable: true,
  17623. configurable: true
  17624. });
  17625. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17626. /**
  17627. * The number (integer) of subdivisions per axis in the partioning space
  17628. */
  17629. get: function () {
  17630. return this._partitioningSubdivisions;
  17631. },
  17632. set: function (nb) {
  17633. this._partitioningSubdivisions = nb;
  17634. },
  17635. enumerable: true,
  17636. configurable: true
  17637. });
  17638. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17639. /**
  17640. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17641. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17642. */
  17643. get: function () {
  17644. return this._partitioningBBoxRatio;
  17645. },
  17646. set: function (ratio) {
  17647. this._partitioningBBoxRatio = ratio;
  17648. },
  17649. enumerable: true,
  17650. configurable: true
  17651. });
  17652. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17653. /**
  17654. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17655. * Works only for updatable meshes.
  17656. * Doesn't work with multi-materials.
  17657. */
  17658. get: function () {
  17659. return this._facetDepthSort;
  17660. },
  17661. set: function (sort) {
  17662. this._facetDepthSort = sort;
  17663. },
  17664. enumerable: true,
  17665. configurable: true
  17666. });
  17667. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17668. /**
  17669. * The location (Vector3) where the facet depth sort must be computed from.
  17670. * By default, the active camera position.
  17671. * Used only when facet depth sort is enabled.
  17672. */
  17673. get: function () {
  17674. return this._facetDepthSortFrom;
  17675. },
  17676. set: function (location) {
  17677. this._facetDepthSortFrom = location;
  17678. },
  17679. enumerable: true,
  17680. configurable: true
  17681. });
  17682. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17683. /**
  17684. * Read-only boolean : is the feature facetData enabled ?
  17685. */
  17686. get: function () {
  17687. return this._facetDataEnabled;
  17688. },
  17689. enumerable: true,
  17690. configurable: true
  17691. });
  17692. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17693. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17694. return false;
  17695. }
  17696. this._markSubMeshesAsMiscDirty();
  17697. return true;
  17698. };
  17699. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17700. set: function (callback) {
  17701. if (this._onCollideObserver) {
  17702. this.onCollideObservable.remove(this._onCollideObserver);
  17703. }
  17704. this._onCollideObserver = this.onCollideObservable.add(callback);
  17705. },
  17706. enumerable: true,
  17707. configurable: true
  17708. });
  17709. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17710. set: function (callback) {
  17711. if (this._onCollisionPositionChangeObserver) {
  17712. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17713. }
  17714. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17715. },
  17716. enumerable: true,
  17717. configurable: true
  17718. });
  17719. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17720. /**
  17721. * 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.
  17722. */
  17723. get: function () {
  17724. return this._isOccluded;
  17725. },
  17726. set: function (value) {
  17727. this._isOccluded = value;
  17728. },
  17729. enumerable: true,
  17730. configurable: true
  17731. });
  17732. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17733. /**
  17734. * Flag to check the progress status of the query
  17735. */
  17736. get: function () {
  17737. return this._isOcclusionQueryInProgress;
  17738. },
  17739. enumerable: true,
  17740. configurable: true
  17741. });
  17742. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17743. /**
  17744. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17745. */
  17746. get: function () {
  17747. return this._visibility;
  17748. },
  17749. /**
  17750. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17751. */
  17752. set: function (value) {
  17753. if (this._visibility === value) {
  17754. return;
  17755. }
  17756. this._visibility = value;
  17757. this._markSubMeshesAsMiscDirty();
  17758. },
  17759. enumerable: true,
  17760. configurable: true
  17761. });
  17762. Object.defineProperty(AbstractMesh.prototype, "material", {
  17763. get: function () {
  17764. return this._material;
  17765. },
  17766. set: function (value) {
  17767. if (this._material === value) {
  17768. return;
  17769. }
  17770. this._material = value;
  17771. if (this.onMaterialChangedObservable.hasObservers) {
  17772. this.onMaterialChangedObservable.notifyObservers(this);
  17773. }
  17774. if (!this.subMeshes) {
  17775. return;
  17776. }
  17777. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17778. var subMesh = _a[_i];
  17779. subMesh.setEffect(null);
  17780. }
  17781. },
  17782. enumerable: true,
  17783. configurable: true
  17784. });
  17785. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17786. get: function () {
  17787. return this._receiveShadows;
  17788. },
  17789. set: function (value) {
  17790. if (this._receiveShadows === value) {
  17791. return;
  17792. }
  17793. this._receiveShadows = value;
  17794. this._markSubMeshesAsLightDirty();
  17795. },
  17796. enumerable: true,
  17797. configurable: true
  17798. });
  17799. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17800. get: function () {
  17801. return this._hasVertexAlpha;
  17802. },
  17803. set: function (value) {
  17804. if (this._hasVertexAlpha === value) {
  17805. return;
  17806. }
  17807. this._hasVertexAlpha = value;
  17808. this._markSubMeshesAsAttributesDirty();
  17809. this._markSubMeshesAsMiscDirty();
  17810. },
  17811. enumerable: true,
  17812. configurable: true
  17813. });
  17814. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17815. get: function () {
  17816. return this._useVertexColors;
  17817. },
  17818. set: function (value) {
  17819. if (this._useVertexColors === value) {
  17820. return;
  17821. }
  17822. this._useVertexColors = value;
  17823. this._markSubMeshesAsAttributesDirty();
  17824. },
  17825. enumerable: true,
  17826. configurable: true
  17827. });
  17828. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17829. get: function () {
  17830. return this._computeBonesUsingShaders;
  17831. },
  17832. set: function (value) {
  17833. if (this._computeBonesUsingShaders === value) {
  17834. return;
  17835. }
  17836. this._computeBonesUsingShaders = value;
  17837. this._markSubMeshesAsAttributesDirty();
  17838. },
  17839. enumerable: true,
  17840. configurable: true
  17841. });
  17842. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17843. get: function () {
  17844. return this._numBoneInfluencers;
  17845. },
  17846. set: function (value) {
  17847. if (this._numBoneInfluencers === value) {
  17848. return;
  17849. }
  17850. this._numBoneInfluencers = value;
  17851. this._markSubMeshesAsAttributesDirty();
  17852. },
  17853. enumerable: true,
  17854. configurable: true
  17855. });
  17856. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17857. get: function () {
  17858. return this._applyFog;
  17859. },
  17860. set: function (value) {
  17861. if (this._applyFog === value) {
  17862. return;
  17863. }
  17864. this._applyFog = value;
  17865. this._markSubMeshesAsMiscDirty();
  17866. },
  17867. enumerable: true,
  17868. configurable: true
  17869. });
  17870. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17871. get: function () {
  17872. return this._layerMask;
  17873. },
  17874. set: function (value) {
  17875. if (value === this._layerMask) {
  17876. return;
  17877. }
  17878. this._layerMask = value;
  17879. this._resyncLightSources();
  17880. },
  17881. enumerable: true,
  17882. configurable: true
  17883. });
  17884. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17885. get: function () {
  17886. return this._collisionMask;
  17887. },
  17888. set: function (mask) {
  17889. this._collisionMask = !isNaN(mask) ? mask : -1;
  17890. },
  17891. enumerable: true,
  17892. configurable: true
  17893. });
  17894. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17895. get: function () {
  17896. return this._collisionGroup;
  17897. },
  17898. set: function (mask) {
  17899. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17900. },
  17901. enumerable: true,
  17902. configurable: true
  17903. });
  17904. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17905. get: function () {
  17906. return null;
  17907. },
  17908. enumerable: true,
  17909. configurable: true
  17910. });
  17911. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17912. get: function () {
  17913. return this._skeleton;
  17914. },
  17915. set: function (value) {
  17916. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17917. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17918. }
  17919. if (value && value.needInitialSkinMatrix) {
  17920. value._registerMeshWithPoseMatrix(this);
  17921. }
  17922. this._skeleton = value;
  17923. if (!this._skeleton) {
  17924. this._bonesTransformMatrices = null;
  17925. }
  17926. this._markSubMeshesAsAttributesDirty();
  17927. },
  17928. enumerable: true,
  17929. configurable: true
  17930. });
  17931. /**
  17932. * Returns the string "AbstractMesh"
  17933. */
  17934. AbstractMesh.prototype.getClassName = function () {
  17935. return "AbstractMesh";
  17936. };
  17937. /**
  17938. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17939. */
  17940. AbstractMesh.prototype.toString = function (fullDetails) {
  17941. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17942. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17943. if (this._skeleton) {
  17944. ret += ", skeleton: " + this._skeleton.name;
  17945. }
  17946. if (fullDetails) {
  17947. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17948. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17949. }
  17950. return ret;
  17951. };
  17952. AbstractMesh.prototype._rebuild = function () {
  17953. if (this._occlusionQuery) {
  17954. this._occlusionQuery = null;
  17955. }
  17956. if (this._edgesRenderer) {
  17957. this._edgesRenderer._rebuild();
  17958. }
  17959. if (!this.subMeshes) {
  17960. return;
  17961. }
  17962. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17963. var subMesh = _a[_i];
  17964. subMesh._rebuild();
  17965. }
  17966. };
  17967. AbstractMesh.prototype._resyncLightSources = function () {
  17968. this._lightSources.length = 0;
  17969. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17970. var light = _a[_i];
  17971. if (!light.isEnabled()) {
  17972. continue;
  17973. }
  17974. if (light.canAffectMesh(this)) {
  17975. this._lightSources.push(light);
  17976. }
  17977. }
  17978. this._markSubMeshesAsLightDirty();
  17979. };
  17980. AbstractMesh.prototype._resyncLighSource = function (light) {
  17981. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17982. var index = this._lightSources.indexOf(light);
  17983. if (index === -1) {
  17984. if (!isIn) {
  17985. return;
  17986. }
  17987. this._lightSources.push(light);
  17988. }
  17989. else {
  17990. if (isIn) {
  17991. return;
  17992. }
  17993. this._lightSources.splice(index, 1);
  17994. }
  17995. this._markSubMeshesAsLightDirty();
  17996. };
  17997. AbstractMesh.prototype._removeLightSource = function (light) {
  17998. var index = this._lightSources.indexOf(light);
  17999. if (index === -1) {
  18000. return;
  18001. }
  18002. this._lightSources.splice(index, 1);
  18003. this._markSubMeshesAsLightDirty();
  18004. };
  18005. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  18006. if (!this.subMeshes) {
  18007. return;
  18008. }
  18009. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18010. var subMesh = _a[_i];
  18011. if (subMesh._materialDefines) {
  18012. func(subMesh._materialDefines);
  18013. }
  18014. }
  18015. };
  18016. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  18017. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  18018. };
  18019. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  18020. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  18021. };
  18022. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  18023. if (!this.subMeshes) {
  18024. return;
  18025. }
  18026. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18027. var subMesh = _a[_i];
  18028. var material = subMesh.getMaterial();
  18029. if (material) {
  18030. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  18031. }
  18032. }
  18033. };
  18034. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  18035. /**
  18036. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18037. * Default : (1.0, 1.0, 1.0)
  18038. */
  18039. get: function () {
  18040. return this._scaling;
  18041. },
  18042. /**
  18043. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18044. * Default : (1.0, 1.0, 1.0)
  18045. */
  18046. set: function (newScaling) {
  18047. this._scaling = newScaling;
  18048. if (this.physicsImpostor) {
  18049. this.physicsImpostor.forceUpdate();
  18050. }
  18051. },
  18052. enumerable: true,
  18053. configurable: true
  18054. });
  18055. // Methods
  18056. /**
  18057. * Disables the mesh edger rendering mode.
  18058. * Returns the AbstractMesh.
  18059. */
  18060. AbstractMesh.prototype.disableEdgesRendering = function () {
  18061. if (this._edgesRenderer) {
  18062. this._edgesRenderer.dispose();
  18063. this._edgesRenderer = null;
  18064. }
  18065. return this;
  18066. };
  18067. /**
  18068. * Enables the edge rendering mode on the mesh.
  18069. * This mode makes the mesh edges visible.
  18070. * Returns the AbstractMesh.
  18071. */
  18072. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  18073. if (epsilon === void 0) { epsilon = 0.95; }
  18074. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  18075. this.disableEdgesRendering();
  18076. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  18077. return this;
  18078. };
  18079. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  18080. /**
  18081. * Returns true if the mesh is blocked. Used by the class Mesh.
  18082. * Returns the boolean `false` by default.
  18083. */
  18084. get: function () {
  18085. return false;
  18086. },
  18087. enumerable: true,
  18088. configurable: true
  18089. });
  18090. /**
  18091. * Returns the mesh itself by default, used by the class Mesh.
  18092. * Returned type : AbstractMesh
  18093. */
  18094. AbstractMesh.prototype.getLOD = function (camera) {
  18095. return this;
  18096. };
  18097. /**
  18098. * Returns 0 by default, used by the class Mesh.
  18099. * Returns an integer.
  18100. */
  18101. AbstractMesh.prototype.getTotalVertices = function () {
  18102. return 0;
  18103. };
  18104. /**
  18105. * Returns null by default, used by the class Mesh.
  18106. * Returned type : integer array
  18107. */
  18108. AbstractMesh.prototype.getIndices = function () {
  18109. return null;
  18110. };
  18111. /**
  18112. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  18113. * Returned type : float array or Float32Array
  18114. */
  18115. AbstractMesh.prototype.getVerticesData = function (kind) {
  18116. return null;
  18117. };
  18118. /**
  18119. * Sets the vertex data of the mesh geometry for the requested `kind`.
  18120. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  18121. * The `data` are either a numeric array either a Float32Array.
  18122. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  18123. * 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).
  18124. * Note that a new underlying VertexBuffer object is created each call.
  18125. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18126. *
  18127. * Possible `kind` values :
  18128. * - BABYLON.VertexBuffer.PositionKind
  18129. * - BABYLON.VertexBuffer.UVKind
  18130. * - BABYLON.VertexBuffer.UV2Kind
  18131. * - BABYLON.VertexBuffer.UV3Kind
  18132. * - BABYLON.VertexBuffer.UV4Kind
  18133. * - BABYLON.VertexBuffer.UV5Kind
  18134. * - BABYLON.VertexBuffer.UV6Kind
  18135. * - BABYLON.VertexBuffer.ColorKind
  18136. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18137. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18138. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18139. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18140. *
  18141. * Returns the Mesh.
  18142. */
  18143. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18144. return this;
  18145. };
  18146. /**
  18147. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18148. * If the mesh has no geometry, it is simply returned as it is.
  18149. * The `data` are either a numeric array either a Float32Array.
  18150. * No new underlying VertexBuffer object is created.
  18151. * 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.
  18152. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18153. *
  18154. * Possible `kind` values :
  18155. * - BABYLON.VertexBuffer.PositionKind
  18156. * - BABYLON.VertexBuffer.UVKind
  18157. * - BABYLON.VertexBuffer.UV2Kind
  18158. * - BABYLON.VertexBuffer.UV3Kind
  18159. * - BABYLON.VertexBuffer.UV4Kind
  18160. * - BABYLON.VertexBuffer.UV5Kind
  18161. * - BABYLON.VertexBuffer.UV6Kind
  18162. * - BABYLON.VertexBuffer.ColorKind
  18163. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18164. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18165. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18166. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18167. *
  18168. * Returns the Mesh.
  18169. */
  18170. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18171. return this;
  18172. };
  18173. /**
  18174. * Sets the mesh indices.
  18175. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  18176. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  18177. * This method creates a new index buffer each call.
  18178. * Returns the Mesh.
  18179. */
  18180. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  18181. return this;
  18182. };
  18183. /** Returns false by default, used by the class Mesh.
  18184. * Returns a boolean
  18185. */
  18186. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  18187. return false;
  18188. };
  18189. /**
  18190. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  18191. * Returns a BoundingInfo
  18192. */
  18193. AbstractMesh.prototype.getBoundingInfo = function () {
  18194. if (this._masterMesh) {
  18195. return this._masterMesh.getBoundingInfo();
  18196. }
  18197. if (!this._boundingInfo) {
  18198. // this._boundingInfo is being created here
  18199. this._updateBoundingInfo();
  18200. }
  18201. // cannot be null.
  18202. return this._boundingInfo;
  18203. };
  18204. /**
  18205. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  18206. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  18207. */
  18208. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  18209. if (includeDescendants === void 0) { includeDescendants = true; }
  18210. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  18211. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  18212. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  18213. if (maxDimension === 0) {
  18214. return this;
  18215. }
  18216. var scale = 1 / maxDimension;
  18217. this.scaling.scaleInPlace(scale);
  18218. return this;
  18219. };
  18220. /**
  18221. * Sets a mesh new object BoundingInfo.
  18222. * Returns the AbstractMesh.
  18223. */
  18224. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  18225. this._boundingInfo = boundingInfo;
  18226. return this;
  18227. };
  18228. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  18229. get: function () {
  18230. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  18231. },
  18232. enumerable: true,
  18233. configurable: true
  18234. });
  18235. AbstractMesh.prototype._preActivate = function () {
  18236. };
  18237. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18238. };
  18239. AbstractMesh.prototype._activate = function (renderId) {
  18240. this._renderId = renderId;
  18241. };
  18242. /**
  18243. * Returns the latest update of the World matrix
  18244. * Returns a Matrix.
  18245. */
  18246. AbstractMesh.prototype.getWorldMatrix = function () {
  18247. if (this._masterMesh) {
  18248. return this._masterMesh.getWorldMatrix();
  18249. }
  18250. return _super.prototype.getWorldMatrix.call(this);
  18251. };
  18252. /**
  18253. * Returns the latest update of the World matrix determinant.
  18254. */
  18255. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  18256. if (this._masterMesh) {
  18257. return this._masterMesh._getWorldMatrixDeterminant();
  18258. }
  18259. return _super.prototype._getWorldMatrixDeterminant.call(this);
  18260. };
  18261. // ================================== Point of View Movement =================================
  18262. /**
  18263. * Perform relative position change from the point of view of behind the front of the mesh.
  18264. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18265. * Supports definition of mesh facing forward or backward.
  18266. * @param {number} amountRight
  18267. * @param {number} amountUp
  18268. * @param {number} amountForward
  18269. *
  18270. * Returns the AbstractMesh.
  18271. */
  18272. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  18273. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  18274. return this;
  18275. };
  18276. /**
  18277. * Calculate relative position change from the point of view of behind the front of the mesh.
  18278. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18279. * Supports definition of mesh facing forward or backward.
  18280. * @param {number} amountRight
  18281. * @param {number} amountUp
  18282. * @param {number} amountForward
  18283. *
  18284. * Returns a new Vector3.
  18285. */
  18286. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  18287. var rotMatrix = new BABYLON.Matrix();
  18288. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18289. rotQuaternion.toRotationMatrix(rotMatrix);
  18290. var translationDelta = BABYLON.Vector3.Zero();
  18291. var defForwardMult = this.definedFacingForward ? -1 : 1;
  18292. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  18293. return translationDelta;
  18294. };
  18295. // ================================== Point of View Rotation =================================
  18296. /**
  18297. * Perform relative rotation change from the point of view of behind the front of the mesh.
  18298. * Supports definition of mesh facing forward or backward.
  18299. * @param {number} flipBack
  18300. * @param {number} twirlClockwise
  18301. * @param {number} tiltRight
  18302. *
  18303. * Returns the AbstractMesh.
  18304. */
  18305. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18306. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  18307. return this;
  18308. };
  18309. /**
  18310. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  18311. * Supports definition of mesh facing forward or backward.
  18312. * @param {number} flipBack
  18313. * @param {number} twirlClockwise
  18314. * @param {number} tiltRight
  18315. *
  18316. * Returns a new Vector3.
  18317. */
  18318. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18319. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18320. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18321. };
  18322. /**
  18323. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18324. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18325. */
  18326. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18327. if (includeDescendants === void 0) { includeDescendants = true; }
  18328. this.computeWorldMatrix(true);
  18329. var min;
  18330. var max;
  18331. var boundingInfo = this.getBoundingInfo();
  18332. if (!this.subMeshes) {
  18333. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18334. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18335. }
  18336. else {
  18337. min = boundingInfo.boundingBox.minimumWorld;
  18338. max = boundingInfo.boundingBox.maximumWorld;
  18339. }
  18340. if (includeDescendants) {
  18341. var descendants = this.getDescendants(false);
  18342. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18343. var descendant = descendants_1[_i];
  18344. var childMesh = descendant;
  18345. childMesh.computeWorldMatrix(true);
  18346. //make sure we have the needed params to get mix and max
  18347. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18348. continue;
  18349. }
  18350. var childBoundingInfo = childMesh.getBoundingInfo();
  18351. var boundingBox = childBoundingInfo.boundingBox;
  18352. var minBox = boundingBox.minimumWorld;
  18353. var maxBox = boundingBox.maximumWorld;
  18354. BABYLON.Tools.CheckExtends(minBox, min, max);
  18355. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18356. }
  18357. }
  18358. return {
  18359. min: min,
  18360. max: max
  18361. };
  18362. };
  18363. /**
  18364. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18365. * Returns the AbstractMesh.
  18366. */
  18367. AbstractMesh.prototype._updateBoundingInfo = function () {
  18368. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18369. this._boundingInfo.update(this.worldMatrixFromCache);
  18370. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18371. return this;
  18372. };
  18373. /**
  18374. * Update a mesh's children BoundingInfo objects only.
  18375. * Returns the AbstractMesh.
  18376. */
  18377. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18378. if (!this.subMeshes) {
  18379. return this;
  18380. }
  18381. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18382. var subMesh = this.subMeshes[subIndex];
  18383. if (!subMesh.IsGlobal) {
  18384. subMesh.updateBoundingInfo(matrix);
  18385. }
  18386. }
  18387. return this;
  18388. };
  18389. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18390. // Bounding info
  18391. this._updateBoundingInfo();
  18392. };
  18393. /**
  18394. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18395. * A mesh is in the frustum if its bounding box intersects the frustum.
  18396. * Boolean returned.
  18397. */
  18398. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18399. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18400. };
  18401. /**
  18402. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18403. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18404. * Boolean returned.
  18405. */
  18406. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18407. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18408. ;
  18409. };
  18410. /**
  18411. * True if the mesh intersects another mesh or a SolidParticle object.
  18412. * 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)
  18413. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18414. * Returns a boolean.
  18415. */
  18416. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18417. if (precise === void 0) { precise = false; }
  18418. if (!this._boundingInfo || !mesh._boundingInfo) {
  18419. return false;
  18420. }
  18421. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18422. return true;
  18423. }
  18424. if (includeDescendants) {
  18425. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18426. var child = _a[_i];
  18427. if (child.intersectsMesh(mesh, precise, true)) {
  18428. return true;
  18429. }
  18430. }
  18431. }
  18432. return false;
  18433. };
  18434. /**
  18435. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18436. * Returns a boolean.
  18437. */
  18438. AbstractMesh.prototype.intersectsPoint = function (point) {
  18439. if (!this._boundingInfo) {
  18440. return false;
  18441. }
  18442. return this._boundingInfo.intersectsPoint(point);
  18443. };
  18444. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18445. return this.physicsImpostor;
  18446. };
  18447. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18448. if (camera === void 0) { camera = null; }
  18449. if (!camera) {
  18450. camera = this.getScene().activeCamera;
  18451. }
  18452. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18453. };
  18454. /**
  18455. * Returns the distance from the mesh to the active camera.
  18456. * Returns a float.
  18457. */
  18458. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18459. if (camera === void 0) { camera = null; }
  18460. if (!camera) {
  18461. camera = this.getScene().activeCamera;
  18462. }
  18463. return this.absolutePosition.subtract(camera.position).length();
  18464. };
  18465. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18466. if (!this.physicsImpostor) {
  18467. return this;
  18468. }
  18469. this.physicsImpostor.applyImpulse(force, contactPoint);
  18470. return this;
  18471. };
  18472. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18473. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18474. return this;
  18475. }
  18476. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18477. mainPivot: pivot1,
  18478. connectedPivot: pivot2,
  18479. nativeParams: options
  18480. });
  18481. return this;
  18482. };
  18483. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18484. // Collisions
  18485. /**
  18486. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18487. * Default `false`.
  18488. */
  18489. get: function () {
  18490. return this._checkCollisions;
  18491. },
  18492. set: function (collisionEnabled) {
  18493. this._checkCollisions = collisionEnabled;
  18494. if (this.getScene().workerCollisions) {
  18495. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18496. }
  18497. },
  18498. enumerable: true,
  18499. configurable: true
  18500. });
  18501. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18502. /**
  18503. * Gets Collider object used to compute collisions (not physics)
  18504. */
  18505. get: function () {
  18506. return this._collider;
  18507. },
  18508. enumerable: true,
  18509. configurable: true
  18510. });
  18511. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18512. var globalPosition = this.getAbsolutePosition();
  18513. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18514. if (!this._collider) {
  18515. this._collider = new BABYLON.Collider();
  18516. }
  18517. this._collider._radius = this.ellipsoid;
  18518. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18519. return this;
  18520. };
  18521. // Submeshes octree
  18522. /**
  18523. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18524. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18525. * Returns an Octree of submeshes.
  18526. */
  18527. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18528. if (maxCapacity === void 0) { maxCapacity = 64; }
  18529. if (maxDepth === void 0) { maxDepth = 2; }
  18530. if (!this._submeshesOctree) {
  18531. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18532. }
  18533. this.computeWorldMatrix(true);
  18534. var boundingInfo = this.getBoundingInfo();
  18535. // Update octree
  18536. var bbox = boundingInfo.boundingBox;
  18537. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18538. return this._submeshesOctree;
  18539. };
  18540. // Collisions
  18541. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18542. this._generatePointsArray();
  18543. if (!this._positions) {
  18544. return this;
  18545. }
  18546. // Transformation
  18547. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18548. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18549. subMesh._lastColliderWorldVertices = [];
  18550. subMesh._trianglePlanes = [];
  18551. var start = subMesh.verticesStart;
  18552. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18553. for (var i = start; i < end; i++) {
  18554. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18555. }
  18556. }
  18557. // Collide
  18558. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18559. if (collider.collisionFound) {
  18560. collider.collidedMesh = this;
  18561. }
  18562. return this;
  18563. };
  18564. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18565. var subMeshes;
  18566. var len;
  18567. // Octrees
  18568. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18569. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18570. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18571. len = intersections.length;
  18572. subMeshes = intersections.data;
  18573. }
  18574. else {
  18575. subMeshes = this.subMeshes;
  18576. len = subMeshes.length;
  18577. }
  18578. for (var index = 0; index < len; index++) {
  18579. var subMesh = subMeshes[index];
  18580. // Bounding test
  18581. if (len > 1 && !subMesh._checkCollision(collider))
  18582. continue;
  18583. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18584. }
  18585. return this;
  18586. };
  18587. AbstractMesh.prototype._checkCollision = function (collider) {
  18588. // Bounding box test
  18589. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18590. return this;
  18591. // Transformation matrix
  18592. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18593. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18594. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18595. return this;
  18596. };
  18597. // Picking
  18598. AbstractMesh.prototype._generatePointsArray = function () {
  18599. return false;
  18600. };
  18601. /**
  18602. * Checks if the passed Ray intersects with the mesh.
  18603. * Returns an object PickingInfo.
  18604. */
  18605. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18606. var pickingInfo = new BABYLON.PickingInfo();
  18607. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18608. return pickingInfo;
  18609. }
  18610. if (!this._generatePointsArray()) {
  18611. return pickingInfo;
  18612. }
  18613. var intersectInfo = null;
  18614. // Octrees
  18615. var subMeshes;
  18616. var len;
  18617. if (this._submeshesOctree && this.useOctreeForPicking) {
  18618. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18619. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18620. len = intersections.length;
  18621. subMeshes = intersections.data;
  18622. }
  18623. else {
  18624. subMeshes = this.subMeshes;
  18625. len = subMeshes.length;
  18626. }
  18627. for (var index = 0; index < len; index++) {
  18628. var subMesh = subMeshes[index];
  18629. // Bounding test
  18630. if (len > 1 && !subMesh.canIntersects(ray))
  18631. continue;
  18632. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18633. if (currentIntersectInfo) {
  18634. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18635. intersectInfo = currentIntersectInfo;
  18636. intersectInfo.subMeshId = index;
  18637. if (fastCheck) {
  18638. break;
  18639. }
  18640. }
  18641. }
  18642. }
  18643. if (intersectInfo) {
  18644. // Get picked point
  18645. var world = this.getWorldMatrix();
  18646. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18647. var direction = ray.direction.clone();
  18648. direction = direction.scale(intersectInfo.distance);
  18649. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18650. var pickedPoint = worldOrigin.add(worldDirection);
  18651. // Return result
  18652. pickingInfo.hit = true;
  18653. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18654. pickingInfo.pickedPoint = pickedPoint;
  18655. pickingInfo.pickedMesh = this;
  18656. pickingInfo.bu = intersectInfo.bu || 0;
  18657. pickingInfo.bv = intersectInfo.bv || 0;
  18658. pickingInfo.faceId = intersectInfo.faceId;
  18659. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18660. return pickingInfo;
  18661. }
  18662. return pickingInfo;
  18663. };
  18664. /**
  18665. * Clones the mesh, used by the class Mesh.
  18666. * Just returns `null` for an AbstractMesh.
  18667. */
  18668. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18669. return null;
  18670. };
  18671. /**
  18672. * Disposes all the mesh submeshes.
  18673. * Returns the AbstractMesh.
  18674. */
  18675. AbstractMesh.prototype.releaseSubMeshes = function () {
  18676. if (this.subMeshes) {
  18677. while (this.subMeshes.length) {
  18678. this.subMeshes[0].dispose();
  18679. }
  18680. }
  18681. else {
  18682. this.subMeshes = new Array();
  18683. }
  18684. return this;
  18685. };
  18686. /**
  18687. * Releases resources associated with this abstract mesh.
  18688. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18689. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18690. */
  18691. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18692. var _this = this;
  18693. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18694. var index;
  18695. // Smart Array Retainers.
  18696. this.getScene().freeActiveMeshes();
  18697. this.getScene().freeRenderingGroups();
  18698. // Action manager
  18699. if (this.actionManager !== undefined && this.actionManager !== null) {
  18700. this.actionManager.dispose();
  18701. this.actionManager = null;
  18702. }
  18703. // Skeleton
  18704. this._skeleton = null;
  18705. // Physics
  18706. if (this.physicsImpostor) {
  18707. this.physicsImpostor.dispose();
  18708. }
  18709. // Intersections in progress
  18710. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18711. var other = this._intersectionsInProgress[index];
  18712. var pos = other._intersectionsInProgress.indexOf(this);
  18713. other._intersectionsInProgress.splice(pos, 1);
  18714. }
  18715. this._intersectionsInProgress = [];
  18716. // Lights
  18717. var lights = this.getScene().lights;
  18718. lights.forEach(function (light) {
  18719. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18720. if (meshIndex !== -1) {
  18721. light.includedOnlyMeshes.splice(meshIndex, 1);
  18722. }
  18723. meshIndex = light.excludedMeshes.indexOf(_this);
  18724. if (meshIndex !== -1) {
  18725. light.excludedMeshes.splice(meshIndex, 1);
  18726. }
  18727. // Shadow generators
  18728. var generator = light.getShadowGenerator();
  18729. if (generator) {
  18730. var shadowMap = generator.getShadowMap();
  18731. if (shadowMap && shadowMap.renderList) {
  18732. meshIndex = shadowMap.renderList.indexOf(_this);
  18733. if (meshIndex !== -1) {
  18734. shadowMap.renderList.splice(meshIndex, 1);
  18735. }
  18736. }
  18737. }
  18738. });
  18739. // Edges
  18740. if (this._edgesRenderer) {
  18741. this._edgesRenderer.dispose();
  18742. this._edgesRenderer = null;
  18743. }
  18744. // SubMeshes
  18745. if (this.getClassName() !== "InstancedMesh") {
  18746. this.releaseSubMeshes();
  18747. }
  18748. // Octree
  18749. var sceneOctree = this.getScene().selectionOctree;
  18750. if (sceneOctree !== undefined && sceneOctree !== null) {
  18751. var index = sceneOctree.dynamicContent.indexOf(this);
  18752. if (index !== -1) {
  18753. sceneOctree.dynamicContent.splice(index, 1);
  18754. }
  18755. }
  18756. // Query
  18757. var engine = this.getScene().getEngine();
  18758. if (this._occlusionQuery) {
  18759. this._isOcclusionQueryInProgress = false;
  18760. engine.deleteQuery(this._occlusionQuery);
  18761. this._occlusionQuery = null;
  18762. }
  18763. // Engine
  18764. engine.wipeCaches();
  18765. // Remove from scene
  18766. this.getScene().removeMesh(this);
  18767. if (disposeMaterialAndTextures) {
  18768. if (this.material) {
  18769. this.material.dispose(false, true);
  18770. }
  18771. }
  18772. if (!doNotRecurse) {
  18773. // Particles
  18774. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18775. if (this.getScene().particleSystems[index].emitter === this) {
  18776. this.getScene().particleSystems[index].dispose();
  18777. index--;
  18778. }
  18779. }
  18780. }
  18781. // facet data
  18782. if (this._facetDataEnabled) {
  18783. this.disableFacetData();
  18784. }
  18785. this.onAfterWorldMatrixUpdateObservable.clear();
  18786. this.onCollideObservable.clear();
  18787. this.onCollisionPositionChangeObservable.clear();
  18788. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18789. };
  18790. /**
  18791. * Adds the passed mesh as a child to the current mesh.
  18792. * Returns the AbstractMesh.
  18793. */
  18794. AbstractMesh.prototype.addChild = function (mesh) {
  18795. mesh.setParent(this);
  18796. return this;
  18797. };
  18798. /**
  18799. * Removes the passed mesh from the current mesh children list.
  18800. * Returns the AbstractMesh.
  18801. */
  18802. AbstractMesh.prototype.removeChild = function (mesh) {
  18803. mesh.setParent(null);
  18804. return this;
  18805. };
  18806. // Facet data
  18807. /**
  18808. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18809. * Returns the AbstractMesh.
  18810. */
  18811. AbstractMesh.prototype._initFacetData = function () {
  18812. if (!this._facetNormals) {
  18813. this._facetNormals = new Array();
  18814. }
  18815. if (!this._facetPositions) {
  18816. this._facetPositions = new Array();
  18817. }
  18818. if (!this._facetPartitioning) {
  18819. this._facetPartitioning = new Array();
  18820. }
  18821. this._facetNb = (this.getIndices().length / 3) | 0;
  18822. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18823. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18824. for (var f = 0; f < this._facetNb; f++) {
  18825. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18826. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18827. }
  18828. this._facetDataEnabled = true;
  18829. return this;
  18830. };
  18831. /**
  18832. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18833. * This method can be called within the render loop.
  18834. * 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.
  18835. * Returns the AbstractMesh.
  18836. */
  18837. AbstractMesh.prototype.updateFacetData = function () {
  18838. if (!this._facetDataEnabled) {
  18839. this._initFacetData();
  18840. }
  18841. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18842. var indices = this.getIndices();
  18843. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18844. var bInfo = this.getBoundingInfo();
  18845. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18846. // init arrays, matrix and sort function on first call
  18847. this._facetDepthSortEnabled = true;
  18848. if (indices instanceof Uint16Array) {
  18849. this._depthSortedIndices = new Uint16Array(indices);
  18850. }
  18851. else if (indices instanceof Uint32Array) {
  18852. this._depthSortedIndices = new Uint32Array(indices);
  18853. }
  18854. else {
  18855. var needs32bits = false;
  18856. for (var i = 0; i < indices.length; i++) {
  18857. if (indices[i] > 65535) {
  18858. needs32bits = true;
  18859. break;
  18860. }
  18861. }
  18862. if (needs32bits) {
  18863. this._depthSortedIndices = new Uint32Array(indices);
  18864. }
  18865. else {
  18866. this._depthSortedIndices = new Uint16Array(indices);
  18867. }
  18868. }
  18869. this._facetDepthSortFunction = function (f1, f2) {
  18870. return (f2.sqDistance - f1.sqDistance);
  18871. };
  18872. if (!this._facetDepthSortFrom) {
  18873. var camera = this.getScene().activeCamera;
  18874. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18875. }
  18876. this._depthSortedFacets = [];
  18877. for (var f = 0; f < this._facetNb; f++) {
  18878. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18879. this._depthSortedFacets.push(depthSortedFacet);
  18880. }
  18881. this._invertedMatrix = BABYLON.Matrix.Identity();
  18882. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18883. }
  18884. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18885. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18886. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18887. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18888. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18889. this._subDiv.max = this._partitioningSubdivisions;
  18890. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18891. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18892. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18893. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18894. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18895. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18896. // set the parameters for ComputeNormals()
  18897. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18898. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18899. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18900. this._facetParameters.bInfo = bInfo;
  18901. this._facetParameters.bbSize = this._bbSize;
  18902. this._facetParameters.subDiv = this._subDiv;
  18903. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18904. this._facetParameters.depthSort = this._facetDepthSort;
  18905. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18906. this.computeWorldMatrix(true);
  18907. this._worldMatrix.invertToRef(this._invertedMatrix);
  18908. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18909. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18910. }
  18911. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18912. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18913. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18914. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18915. var l = (this._depthSortedIndices.length / 3) | 0;
  18916. for (var f = 0; f < l; f++) {
  18917. var sind = this._depthSortedFacets[f].ind;
  18918. this._depthSortedIndices[f * 3] = indices[sind];
  18919. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18920. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18921. }
  18922. this.updateIndices(this._depthSortedIndices);
  18923. }
  18924. return this;
  18925. };
  18926. /**
  18927. * Returns the facetLocalNormals array.
  18928. * The normals are expressed in the mesh local space.
  18929. */
  18930. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18931. if (!this._facetNormals) {
  18932. this.updateFacetData();
  18933. }
  18934. return this._facetNormals;
  18935. };
  18936. /**
  18937. * Returns the facetLocalPositions array.
  18938. * The facet positions are expressed in the mesh local space.
  18939. */
  18940. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18941. if (!this._facetPositions) {
  18942. this.updateFacetData();
  18943. }
  18944. return this._facetPositions;
  18945. };
  18946. /**
  18947. * Returns the facetLocalPartioning array.
  18948. */
  18949. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18950. if (!this._facetPartitioning) {
  18951. this.updateFacetData();
  18952. }
  18953. return this._facetPartitioning;
  18954. };
  18955. /**
  18956. * Returns the i-th facet position in the world system.
  18957. * This method allocates a new Vector3 per call.
  18958. */
  18959. AbstractMesh.prototype.getFacetPosition = function (i) {
  18960. var pos = BABYLON.Vector3.Zero();
  18961. this.getFacetPositionToRef(i, pos);
  18962. return pos;
  18963. };
  18964. /**
  18965. * Sets the reference Vector3 with the i-th facet position in the world system.
  18966. * Returns the AbstractMesh.
  18967. */
  18968. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18969. var localPos = (this.getFacetLocalPositions())[i];
  18970. var world = this.getWorldMatrix();
  18971. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18972. return this;
  18973. };
  18974. /**
  18975. * Returns the i-th facet normal in the world system.
  18976. * This method allocates a new Vector3 per call.
  18977. */
  18978. AbstractMesh.prototype.getFacetNormal = function (i) {
  18979. var norm = BABYLON.Vector3.Zero();
  18980. this.getFacetNormalToRef(i, norm);
  18981. return norm;
  18982. };
  18983. /**
  18984. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18985. * Returns the AbstractMesh.
  18986. */
  18987. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18988. var localNorm = (this.getFacetLocalNormals())[i];
  18989. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18990. return this;
  18991. };
  18992. /**
  18993. * 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).
  18994. */
  18995. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18996. var bInfo = this.getBoundingInfo();
  18997. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18998. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18999. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  19000. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  19001. return null;
  19002. }
  19003. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  19004. };
  19005. /**
  19006. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  19007. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  19008. * 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.
  19009. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19010. * 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.
  19011. */
  19012. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  19013. if (checkFace === void 0) { checkFace = false; }
  19014. if (facing === void 0) { facing = true; }
  19015. var world = this.getWorldMatrix();
  19016. var invMat = BABYLON.Tmp.Matrix[5];
  19017. world.invertToRef(invMat);
  19018. var invVect = BABYLON.Tmp.Vector3[8];
  19019. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  19020. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  19021. if (projected) {
  19022. // tranform the local computed projected vector to world coordinates
  19023. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  19024. }
  19025. return closest;
  19026. };
  19027. /**
  19028. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  19029. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  19030. * 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.
  19031. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19032. * 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.
  19033. */
  19034. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  19035. if (checkFace === void 0) { checkFace = false; }
  19036. if (facing === void 0) { facing = true; }
  19037. var closest = null;
  19038. var tmpx = 0.0;
  19039. var tmpy = 0.0;
  19040. var tmpz = 0.0;
  19041. var d = 0.0; // tmp dot facet normal * facet position
  19042. var t0 = 0.0;
  19043. var projx = 0.0;
  19044. var projy = 0.0;
  19045. var projz = 0.0;
  19046. // Get all the facets in the same partitioning block than (x, y, z)
  19047. var facetPositions = this.getFacetLocalPositions();
  19048. var facetNormals = this.getFacetLocalNormals();
  19049. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  19050. if (!facetsInBlock) {
  19051. return null;
  19052. }
  19053. // Get the closest facet to (x, y, z)
  19054. var shortest = Number.MAX_VALUE; // init distance vars
  19055. var tmpDistance = shortest;
  19056. var fib; // current facet in the block
  19057. var norm; // current facet normal
  19058. var p0; // current facet barycenter position
  19059. // loop on all the facets in the current partitioning block
  19060. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  19061. fib = facetsInBlock[idx];
  19062. norm = facetNormals[fib];
  19063. p0 = facetPositions[fib];
  19064. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  19065. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  19066. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  19067. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  19068. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  19069. projx = x + norm.x * t0;
  19070. projy = y + norm.y * t0;
  19071. projz = z + norm.z * t0;
  19072. tmpx = projx - x;
  19073. tmpy = projy - y;
  19074. tmpz = projz - z;
  19075. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  19076. if (tmpDistance < shortest) {
  19077. shortest = tmpDistance;
  19078. closest = fib;
  19079. if (projected) {
  19080. projected.x = projx;
  19081. projected.y = projy;
  19082. projected.z = projz;
  19083. }
  19084. }
  19085. }
  19086. }
  19087. return closest;
  19088. };
  19089. /**
  19090. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  19091. */
  19092. AbstractMesh.prototype.getFacetDataParameters = function () {
  19093. return this._facetParameters;
  19094. };
  19095. /**
  19096. * Disables the feature FacetData and frees the related memory.
  19097. * Returns the AbstractMesh.
  19098. */
  19099. AbstractMesh.prototype.disableFacetData = function () {
  19100. if (this._facetDataEnabled) {
  19101. this._facetDataEnabled = false;
  19102. this._facetPositions = new Array();
  19103. this._facetNormals = new Array();
  19104. this._facetPartitioning = new Array();
  19105. this._facetParameters = null;
  19106. this._depthSortedIndices = new Uint32Array(0);
  19107. }
  19108. return this;
  19109. };
  19110. /**
  19111. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  19112. * Returns the mesh.
  19113. */
  19114. AbstractMesh.prototype.updateIndices = function (indices) {
  19115. return this;
  19116. };
  19117. /**
  19118. * The mesh Geometry. Actually used by the Mesh object.
  19119. * Returns a blank geometry object.
  19120. */
  19121. /**
  19122. * Creates new normals data for the mesh.
  19123. * @param updatable.
  19124. */
  19125. AbstractMesh.prototype.createNormals = function (updatable) {
  19126. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19127. var indices = this.getIndices();
  19128. var normals;
  19129. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19130. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19131. }
  19132. else {
  19133. normals = [];
  19134. }
  19135. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  19136. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  19137. };
  19138. /**
  19139. * Align the mesh with a normal.
  19140. * Returns the mesh.
  19141. */
  19142. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  19143. if (!upDirection) {
  19144. upDirection = BABYLON.Axis.Y;
  19145. }
  19146. var axisX = BABYLON.Tmp.Vector3[0];
  19147. var axisZ = BABYLON.Tmp.Vector3[1];
  19148. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  19149. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  19150. if (this.rotationQuaternion) {
  19151. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  19152. }
  19153. else {
  19154. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  19155. }
  19156. return this;
  19157. };
  19158. AbstractMesh.prototype.checkOcclusionQuery = function () {
  19159. var engine = this.getEngine();
  19160. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  19161. this._isOccluded = false;
  19162. return;
  19163. }
  19164. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  19165. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  19166. if (isOcclusionQueryAvailable) {
  19167. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  19168. this._isOcclusionQueryInProgress = false;
  19169. this._occlusionInternalRetryCounter = 0;
  19170. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  19171. }
  19172. else {
  19173. this._occlusionInternalRetryCounter++;
  19174. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  19175. this._isOcclusionQueryInProgress = false;
  19176. this._occlusionInternalRetryCounter = 0;
  19177. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  19178. // if strict continue the last state of the object.
  19179. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  19180. }
  19181. else {
  19182. return;
  19183. }
  19184. }
  19185. }
  19186. var scene = this.getScene();
  19187. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  19188. if (!this._occlusionQuery) {
  19189. this._occlusionQuery = engine.createQuery();
  19190. }
  19191. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  19192. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  19193. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  19194. this._isOcclusionQueryInProgress = true;
  19195. };
  19196. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  19197. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  19198. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  19199. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  19200. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  19201. return AbstractMesh;
  19202. }(BABYLON.TransformNode));
  19203. BABYLON.AbstractMesh = AbstractMesh;
  19204. })(BABYLON || (BABYLON = {}));
  19205. //# sourceMappingURL=babylon.abstractMesh.js.map
  19206. "use strict";
  19207. var BABYLON;
  19208. (function (BABYLON) {
  19209. /**
  19210. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  19211. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  19212. * 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.
  19213. */
  19214. var Light = /** @class */ (function (_super) {
  19215. __extends(Light, _super);
  19216. /**
  19217. * Creates a Light object in the scene.
  19218. * Documentation : http://doc.babylonjs.com/tutorials/lights
  19219. * @param name The firendly name of the light
  19220. * @param scene The scene the light belongs too
  19221. */
  19222. function Light(name, scene) {
  19223. var _this = _super.call(this, name, scene) || this;
  19224. /**
  19225. * Diffuse gives the basic color to an object.
  19226. */
  19227. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  19228. /**
  19229. * Specular produces a highlight color on an object.
  19230. * Note: This is note affecting PBR materials.
  19231. */
  19232. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  19233. /**
  19234. * Strength of the light.
  19235. * Note: By default it is define in the framework own unit.
  19236. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  19237. */
  19238. _this.intensity = 1.0;
  19239. /**
  19240. * Defines how far from the source the light is impacting in scene units.
  19241. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  19242. */
  19243. _this.range = Number.MAX_VALUE;
  19244. /**
  19245. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  19246. * of light.
  19247. */
  19248. _this._photometricScale = 1.0;
  19249. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  19250. _this._radius = 0.00001;
  19251. /**
  19252. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  19253. * exceeding the number allowed of the materials.
  19254. */
  19255. _this.renderPriority = 0;
  19256. /**
  19257. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  19258. * the current shadow generator.
  19259. */
  19260. _this.shadowEnabled = true;
  19261. _this._excludeWithLayerMask = 0;
  19262. _this._includeOnlyWithLayerMask = 0;
  19263. _this._lightmapMode = 0;
  19264. /**
  19265. * @ignore Internal use only.
  19266. */
  19267. _this._excludedMeshesIds = new Array();
  19268. /**
  19269. * @ignore Internal use only.
  19270. */
  19271. _this._includedOnlyMeshesIds = new Array();
  19272. _this.getScene().addLight(_this);
  19273. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19274. _this._buildUniformLayout();
  19275. _this.includedOnlyMeshes = new Array();
  19276. _this.excludedMeshes = new Array();
  19277. _this._resyncMeshes();
  19278. return _this;
  19279. }
  19280. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19281. /**
  19282. * If every light affecting the material is in this lightmapMode,
  19283. * material.lightmapTexture adds or multiplies
  19284. * (depends on material.useLightmapAsShadowmap)
  19285. * after every other light calculations.
  19286. */
  19287. get: function () {
  19288. return Light._LIGHTMAP_DEFAULT;
  19289. },
  19290. enumerable: true,
  19291. configurable: true
  19292. });
  19293. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19294. /**
  19295. * material.lightmapTexture as only diffuse lighting from this light
  19296. * adds only specular lighting from this light
  19297. * adds dynamic shadows
  19298. */
  19299. get: function () {
  19300. return Light._LIGHTMAP_SPECULAR;
  19301. },
  19302. enumerable: true,
  19303. configurable: true
  19304. });
  19305. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19306. /**
  19307. * material.lightmapTexture as only lighting
  19308. * no light calculation from this light
  19309. * only adds dynamic shadows from this light
  19310. */
  19311. get: function () {
  19312. return Light._LIGHTMAP_SHADOWSONLY;
  19313. },
  19314. enumerable: true,
  19315. configurable: true
  19316. });
  19317. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19318. /**
  19319. * Each light type uses the default quantity according to its type:
  19320. * point/spot lights use luminous intensity
  19321. * directional lights use illuminance
  19322. */
  19323. get: function () {
  19324. return Light._INTENSITYMODE_AUTOMATIC;
  19325. },
  19326. enumerable: true,
  19327. configurable: true
  19328. });
  19329. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19330. /**
  19331. * lumen (lm)
  19332. */
  19333. get: function () {
  19334. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19335. },
  19336. enumerable: true,
  19337. configurable: true
  19338. });
  19339. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19340. /**
  19341. * candela (lm/sr)
  19342. */
  19343. get: function () {
  19344. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19345. },
  19346. enumerable: true,
  19347. configurable: true
  19348. });
  19349. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19350. /**
  19351. * lux (lm/m^2)
  19352. */
  19353. get: function () {
  19354. return Light._INTENSITYMODE_ILLUMINANCE;
  19355. },
  19356. enumerable: true,
  19357. configurable: true
  19358. });
  19359. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19360. /**
  19361. * nit (cd/m^2)
  19362. */
  19363. get: function () {
  19364. return Light._INTENSITYMODE_LUMINANCE;
  19365. },
  19366. enumerable: true,
  19367. configurable: true
  19368. });
  19369. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19370. /**
  19371. * Light type const id of the point light.
  19372. */
  19373. get: function () {
  19374. return Light._LIGHTTYPEID_POINTLIGHT;
  19375. },
  19376. enumerable: true,
  19377. configurable: true
  19378. });
  19379. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19380. /**
  19381. * Light type const id of the directional light.
  19382. */
  19383. get: function () {
  19384. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19385. },
  19386. enumerable: true,
  19387. configurable: true
  19388. });
  19389. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19390. /**
  19391. * Light type const id of the spot light.
  19392. */
  19393. get: function () {
  19394. return Light._LIGHTTYPEID_SPOTLIGHT;
  19395. },
  19396. enumerable: true,
  19397. configurable: true
  19398. });
  19399. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19400. /**
  19401. * Light type const id of the hemispheric light.
  19402. */
  19403. get: function () {
  19404. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19405. },
  19406. enumerable: true,
  19407. configurable: true
  19408. });
  19409. Object.defineProperty(Light.prototype, "intensityMode", {
  19410. /**
  19411. * Gets the photometric scale used to interpret the intensity.
  19412. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19413. */
  19414. get: function () {
  19415. return this._intensityMode;
  19416. },
  19417. /**
  19418. * Sets the photometric scale used to interpret the intensity.
  19419. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19420. */
  19421. set: function (value) {
  19422. this._intensityMode = value;
  19423. this._computePhotometricScale();
  19424. },
  19425. enumerable: true,
  19426. configurable: true
  19427. });
  19428. ;
  19429. ;
  19430. Object.defineProperty(Light.prototype, "radius", {
  19431. /**
  19432. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19433. */
  19434. get: function () {
  19435. return this._radius;
  19436. },
  19437. /**
  19438. * sets the light radius used by PBR Materials to simulate soft area lights.
  19439. */
  19440. set: function (value) {
  19441. this._radius = value;
  19442. this._computePhotometricScale();
  19443. },
  19444. enumerable: true,
  19445. configurable: true
  19446. });
  19447. ;
  19448. ;
  19449. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19450. /**
  19451. * Gets the only meshes impacted by this light.
  19452. */
  19453. get: function () {
  19454. return this._includedOnlyMeshes;
  19455. },
  19456. /**
  19457. * Sets the only meshes impacted by this light.
  19458. */
  19459. set: function (value) {
  19460. this._includedOnlyMeshes = value;
  19461. this._hookArrayForIncludedOnly(value);
  19462. },
  19463. enumerable: true,
  19464. configurable: true
  19465. });
  19466. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19467. /**
  19468. * Gets the meshes not impacted by this light.
  19469. */
  19470. get: function () {
  19471. return this._excludedMeshes;
  19472. },
  19473. /**
  19474. * Sets the meshes not impacted by this light.
  19475. */
  19476. set: function (value) {
  19477. this._excludedMeshes = value;
  19478. this._hookArrayForExcluded(value);
  19479. },
  19480. enumerable: true,
  19481. configurable: true
  19482. });
  19483. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19484. /**
  19485. * Gets the layer id use to find what meshes are not impacted by the light.
  19486. * Inactive if 0
  19487. */
  19488. get: function () {
  19489. return this._excludeWithLayerMask;
  19490. },
  19491. /**
  19492. * Sets the layer id use to find what meshes are not impacted by the light.
  19493. * Inactive if 0
  19494. */
  19495. set: function (value) {
  19496. this._excludeWithLayerMask = value;
  19497. this._resyncMeshes();
  19498. },
  19499. enumerable: true,
  19500. configurable: true
  19501. });
  19502. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19503. /**
  19504. * Gets the layer id use to find what meshes are impacted by the light.
  19505. * Inactive if 0
  19506. */
  19507. get: function () {
  19508. return this._includeOnlyWithLayerMask;
  19509. },
  19510. /**
  19511. * Sets the layer id use to find what meshes are impacted by the light.
  19512. * Inactive if 0
  19513. */
  19514. set: function (value) {
  19515. this._includeOnlyWithLayerMask = value;
  19516. this._resyncMeshes();
  19517. },
  19518. enumerable: true,
  19519. configurable: true
  19520. });
  19521. Object.defineProperty(Light.prototype, "lightmapMode", {
  19522. /**
  19523. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19524. */
  19525. get: function () {
  19526. return this._lightmapMode;
  19527. },
  19528. /**
  19529. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19530. */
  19531. set: function (value) {
  19532. if (this._lightmapMode === value) {
  19533. return;
  19534. }
  19535. this._lightmapMode = value;
  19536. this._markMeshesAsLightDirty();
  19537. },
  19538. enumerable: true,
  19539. configurable: true
  19540. });
  19541. /**
  19542. * Returns the string "Light".
  19543. * @returns the class name
  19544. */
  19545. Light.prototype.getClassName = function () {
  19546. return "Light";
  19547. };
  19548. /**
  19549. * Converts the light information to a readable string for debug purpose.
  19550. * @param fullDetails Supports for multiple levels of logging within scene loading
  19551. * @returns the human readable light info
  19552. */
  19553. Light.prototype.toString = function (fullDetails) {
  19554. var ret = "Name: " + this.name;
  19555. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19556. if (this.animations) {
  19557. for (var i = 0; i < this.animations.length; i++) {
  19558. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19559. }
  19560. }
  19561. if (fullDetails) {
  19562. }
  19563. return ret;
  19564. };
  19565. /**
  19566. * Set the enabled state of this node.
  19567. * @param value - the new enabled state
  19568. * @see isEnabled
  19569. */
  19570. Light.prototype.setEnabled = function (value) {
  19571. _super.prototype.setEnabled.call(this, value);
  19572. this._resyncMeshes();
  19573. };
  19574. /**
  19575. * Returns the Light associated shadow generator if any.
  19576. * @return the associated shadow generator.
  19577. */
  19578. Light.prototype.getShadowGenerator = function () {
  19579. return this._shadowGenerator;
  19580. };
  19581. /**
  19582. * Returns a Vector3, the absolute light position in the World.
  19583. * @returns the world space position of the light
  19584. */
  19585. Light.prototype.getAbsolutePosition = function () {
  19586. return BABYLON.Vector3.Zero();
  19587. };
  19588. /**
  19589. * Specifies if the light will affect the passed mesh.
  19590. * @param mesh The mesh to test against the light
  19591. * @return true the mesh is affected otherwise, false.
  19592. */
  19593. Light.prototype.canAffectMesh = function (mesh) {
  19594. if (!mesh) {
  19595. return true;
  19596. }
  19597. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19598. return false;
  19599. }
  19600. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19601. return false;
  19602. }
  19603. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19604. return false;
  19605. }
  19606. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19607. return false;
  19608. }
  19609. return true;
  19610. };
  19611. /**
  19612. * Computes and Returns the light World matrix.
  19613. * @returns the world matrix
  19614. */
  19615. Light.prototype.getWorldMatrix = function () {
  19616. this._currentRenderId = this.getScene().getRenderId();
  19617. var worldMatrix = this._getWorldMatrix();
  19618. if (this.parent && this.parent.getWorldMatrix) {
  19619. if (!this._parentedWorldMatrix) {
  19620. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19621. }
  19622. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19623. this._markSyncedWithParent();
  19624. return this._parentedWorldMatrix;
  19625. }
  19626. return worldMatrix;
  19627. };
  19628. /**
  19629. * Sort function to order lights for rendering.
  19630. * @param a First Light object to compare to second.
  19631. * @param b Second Light object to compare first.
  19632. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19633. */
  19634. Light.CompareLightsPriority = function (a, b) {
  19635. //shadow-casting lights have priority over non-shadow-casting lights
  19636. //the renderPrioirty is a secondary sort criterion
  19637. if (a.shadowEnabled !== b.shadowEnabled) {
  19638. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19639. }
  19640. return b.renderPriority - a.renderPriority;
  19641. };
  19642. /**
  19643. * Releases resources associated with this node.
  19644. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19645. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19646. */
  19647. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19648. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19649. if (this._shadowGenerator) {
  19650. this._shadowGenerator.dispose();
  19651. this._shadowGenerator = null;
  19652. }
  19653. // Animations
  19654. this.getScene().stopAnimation(this);
  19655. // Remove from meshes
  19656. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19657. var mesh = _a[_i];
  19658. mesh._removeLightSource(this);
  19659. }
  19660. this._uniformBuffer.dispose();
  19661. // Remove from scene
  19662. this.getScene().removeLight(this);
  19663. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19664. };
  19665. /**
  19666. * Returns the light type ID (integer).
  19667. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19668. */
  19669. Light.prototype.getTypeID = function () {
  19670. return 0;
  19671. };
  19672. /**
  19673. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19674. * @returns the scaled intensity in intensity mode unit
  19675. */
  19676. Light.prototype.getScaledIntensity = function () {
  19677. return this._photometricScale * this.intensity;
  19678. };
  19679. /**
  19680. * Returns a new Light object, named "name", from the current one.
  19681. * @param name The name of the cloned light
  19682. * @returns the new created light
  19683. */
  19684. Light.prototype.clone = function (name) {
  19685. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19686. if (!constructor) {
  19687. return null;
  19688. }
  19689. return BABYLON.SerializationHelper.Clone(constructor, this);
  19690. };
  19691. /**
  19692. * Serializes the current light into a Serialization object.
  19693. * @returns the serialized object.
  19694. */
  19695. Light.prototype.serialize = function () {
  19696. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19697. // Type
  19698. serializationObject.type = this.getTypeID();
  19699. // Parent
  19700. if (this.parent) {
  19701. serializationObject.parentId = this.parent.id;
  19702. }
  19703. // Inclusion / exclusions
  19704. if (this.excludedMeshes.length > 0) {
  19705. serializationObject.excludedMeshesIds = [];
  19706. this.excludedMeshes.forEach(function (mesh) {
  19707. serializationObject.excludedMeshesIds.push(mesh.id);
  19708. });
  19709. }
  19710. if (this.includedOnlyMeshes.length > 0) {
  19711. serializationObject.includedOnlyMeshesIds = [];
  19712. this.includedOnlyMeshes.forEach(function (mesh) {
  19713. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19714. });
  19715. }
  19716. // Animations
  19717. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19718. serializationObject.ranges = this.serializeAnimationRanges();
  19719. return serializationObject;
  19720. };
  19721. /**
  19722. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19723. * This new light is named "name" and added to the passed scene.
  19724. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19725. * @param name The friendly name of the light
  19726. * @param scene The scene the new light will belong to
  19727. * @returns the constructor function
  19728. */
  19729. Light.GetConstructorFromName = function (type, name, scene) {
  19730. switch (type) {
  19731. case 0:
  19732. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19733. case 1:
  19734. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19735. case 2:
  19736. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19737. case 3:
  19738. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19739. }
  19740. return null;
  19741. };
  19742. /**
  19743. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19744. * @param parsedLight The JSON representation of the light
  19745. * @param scene The scene to create the parsed light in
  19746. * @returns the created light after parsing
  19747. */
  19748. Light.Parse = function (parsedLight, scene) {
  19749. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19750. if (!constructor) {
  19751. return null;
  19752. }
  19753. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19754. // Inclusion / exclusions
  19755. if (parsedLight.excludedMeshesIds) {
  19756. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19757. }
  19758. if (parsedLight.includedOnlyMeshesIds) {
  19759. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19760. }
  19761. // Parent
  19762. if (parsedLight.parentId) {
  19763. light._waitingParentId = parsedLight.parentId;
  19764. }
  19765. // Animations
  19766. if (parsedLight.animations) {
  19767. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19768. var parsedAnimation = parsedLight.animations[animationIndex];
  19769. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19770. }
  19771. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19772. }
  19773. if (parsedLight.autoAnimate) {
  19774. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19775. }
  19776. return light;
  19777. };
  19778. Light.prototype._hookArrayForExcluded = function (array) {
  19779. var _this = this;
  19780. var oldPush = array.push;
  19781. array.push = function () {
  19782. var items = [];
  19783. for (var _i = 0; _i < arguments.length; _i++) {
  19784. items[_i] = arguments[_i];
  19785. }
  19786. var result = oldPush.apply(array, items);
  19787. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19788. var item = items_1[_a];
  19789. item._resyncLighSource(_this);
  19790. }
  19791. return result;
  19792. };
  19793. var oldSplice = array.splice;
  19794. array.splice = function (index, deleteCount) {
  19795. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19796. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19797. var item = deleted_1[_i];
  19798. item._resyncLighSource(_this);
  19799. }
  19800. return deleted;
  19801. };
  19802. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19803. var item = array_1[_i];
  19804. item._resyncLighSource(this);
  19805. }
  19806. };
  19807. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19808. var _this = this;
  19809. var oldPush = array.push;
  19810. array.push = function () {
  19811. var items = [];
  19812. for (var _i = 0; _i < arguments.length; _i++) {
  19813. items[_i] = arguments[_i];
  19814. }
  19815. var result = oldPush.apply(array, items);
  19816. _this._resyncMeshes();
  19817. return result;
  19818. };
  19819. var oldSplice = array.splice;
  19820. array.splice = function (index, deleteCount) {
  19821. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19822. _this._resyncMeshes();
  19823. return deleted;
  19824. };
  19825. this._resyncMeshes();
  19826. };
  19827. Light.prototype._resyncMeshes = function () {
  19828. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19829. var mesh = _a[_i];
  19830. mesh._resyncLighSource(this);
  19831. }
  19832. };
  19833. /**
  19834. * Forces the meshes to update their light related information in their rendering used effects
  19835. * @ignore Internal Use Only
  19836. */
  19837. Light.prototype._markMeshesAsLightDirty = function () {
  19838. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19839. var mesh = _a[_i];
  19840. if (mesh._lightSources.indexOf(this) !== -1) {
  19841. mesh._markSubMeshesAsLightDirty();
  19842. }
  19843. }
  19844. };
  19845. /**
  19846. * Recomputes the cached photometric scale if needed.
  19847. */
  19848. Light.prototype._computePhotometricScale = function () {
  19849. this._photometricScale = this._getPhotometricScale();
  19850. this.getScene().resetCachedMaterial();
  19851. };
  19852. /**
  19853. * Returns the Photometric Scale according to the light type and intensity mode.
  19854. */
  19855. Light.prototype._getPhotometricScale = function () {
  19856. var photometricScale = 0.0;
  19857. var lightTypeID = this.getTypeID();
  19858. //get photometric mode
  19859. var photometricMode = this.intensityMode;
  19860. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19861. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19862. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19863. }
  19864. else {
  19865. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19866. }
  19867. }
  19868. //compute photometric scale
  19869. switch (lightTypeID) {
  19870. case Light.LIGHTTYPEID_POINTLIGHT:
  19871. case Light.LIGHTTYPEID_SPOTLIGHT:
  19872. switch (photometricMode) {
  19873. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19874. photometricScale = 1.0 / (4.0 * Math.PI);
  19875. break;
  19876. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19877. photometricScale = 1.0;
  19878. break;
  19879. case Light.INTENSITYMODE_LUMINANCE:
  19880. photometricScale = this.radius * this.radius;
  19881. break;
  19882. }
  19883. break;
  19884. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19885. switch (photometricMode) {
  19886. case Light.INTENSITYMODE_ILLUMINANCE:
  19887. photometricScale = 1.0;
  19888. break;
  19889. case Light.INTENSITYMODE_LUMINANCE:
  19890. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19891. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19892. var apexAngleRadians = this.radius;
  19893. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19894. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19895. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19896. photometricScale = solidAngle;
  19897. break;
  19898. }
  19899. break;
  19900. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19901. // No fall off in hemisperic light.
  19902. photometricScale = 1.0;
  19903. break;
  19904. }
  19905. return photometricScale;
  19906. };
  19907. /**
  19908. * Reorder the light in the scene according to their defined priority.
  19909. * @ignore Internal Use Only
  19910. */
  19911. Light.prototype._reorderLightsInScene = function () {
  19912. var scene = this.getScene();
  19913. if (this._renderPriority != 0) {
  19914. scene.requireLightSorting = true;
  19915. }
  19916. this.getScene().sortLightsByPriority();
  19917. };
  19918. //lightmapMode Consts
  19919. Light._LIGHTMAP_DEFAULT = 0;
  19920. Light._LIGHTMAP_SPECULAR = 1;
  19921. Light._LIGHTMAP_SHADOWSONLY = 2;
  19922. // Intensity Mode Consts
  19923. Light._INTENSITYMODE_AUTOMATIC = 0;
  19924. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19925. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19926. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19927. Light._INTENSITYMODE_LUMINANCE = 4;
  19928. // Light types ids const.
  19929. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19930. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19931. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19932. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19933. __decorate([
  19934. BABYLON.serializeAsColor3()
  19935. ], Light.prototype, "diffuse", void 0);
  19936. __decorate([
  19937. BABYLON.serializeAsColor3()
  19938. ], Light.prototype, "specular", void 0);
  19939. __decorate([
  19940. BABYLON.serialize()
  19941. ], Light.prototype, "intensity", void 0);
  19942. __decorate([
  19943. BABYLON.serialize()
  19944. ], Light.prototype, "range", void 0);
  19945. __decorate([
  19946. BABYLON.serialize()
  19947. ], Light.prototype, "intensityMode", null);
  19948. __decorate([
  19949. BABYLON.serialize()
  19950. ], Light.prototype, "radius", null);
  19951. __decorate([
  19952. BABYLON.serialize()
  19953. ], Light.prototype, "_renderPriority", void 0);
  19954. __decorate([
  19955. BABYLON.expandToProperty("_reorderLightsInScene")
  19956. ], Light.prototype, "renderPriority", void 0);
  19957. __decorate([
  19958. BABYLON.serialize()
  19959. ], Light.prototype, "shadowEnabled", void 0);
  19960. __decorate([
  19961. BABYLON.serialize("excludeWithLayerMask")
  19962. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19963. __decorate([
  19964. BABYLON.serialize("includeOnlyWithLayerMask")
  19965. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19966. __decorate([
  19967. BABYLON.serialize("lightmapMode")
  19968. ], Light.prototype, "_lightmapMode", void 0);
  19969. return Light;
  19970. }(BABYLON.Node));
  19971. BABYLON.Light = Light;
  19972. })(BABYLON || (BABYLON = {}));
  19973. //# sourceMappingURL=babylon.light.js.map
  19974. "use strict";
  19975. var BABYLON;
  19976. (function (BABYLON) {
  19977. var Camera = /** @class */ (function (_super) {
  19978. __extends(Camera, _super);
  19979. function Camera(name, position, scene) {
  19980. var _this = _super.call(this, name, scene) || this;
  19981. /**
  19982. * The vector the camera should consider as up.
  19983. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19984. */
  19985. _this.upVector = BABYLON.Vector3.Up();
  19986. _this.orthoLeft = null;
  19987. _this.orthoRight = null;
  19988. _this.orthoBottom = null;
  19989. _this.orthoTop = null;
  19990. /**
  19991. * FOV is set in Radians. (default is 0.8)
  19992. */
  19993. _this.fov = 0.8;
  19994. _this.minZ = 1;
  19995. _this.maxZ = 10000.0;
  19996. _this.inertia = 0.9;
  19997. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19998. _this.isIntermediate = false;
  19999. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  20000. /**
  20001. * Restricts the camera to viewing objects with the same layerMask.
  20002. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  20003. */
  20004. _this.layerMask = 0x0FFFFFFF;
  20005. /**
  20006. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  20007. */
  20008. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  20009. // Camera rig members
  20010. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  20011. _this._rigCameras = new Array();
  20012. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  20013. _this._skipRendering = false;
  20014. _this.customRenderTargets = new Array();
  20015. // Observables
  20016. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  20017. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  20018. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  20019. _this.onRestoreStateObservable = new BABYLON.Observable();
  20020. // Cache
  20021. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  20022. _this._projectionMatrix = new BABYLON.Matrix();
  20023. _this._doNotComputeProjectionMatrix = false;
  20024. _this._postProcesses = new Array();
  20025. _this._transformMatrix = BABYLON.Matrix.Zero();
  20026. _this._activeMeshes = new BABYLON.SmartArray(256);
  20027. _this._globalPosition = BABYLON.Vector3.Zero();
  20028. _this._refreshFrustumPlanes = true;
  20029. _this.getScene().addCamera(_this);
  20030. if (!_this.getScene().activeCamera) {
  20031. _this.getScene().activeCamera = _this;
  20032. }
  20033. _this.position = position;
  20034. return _this;
  20035. }
  20036. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  20037. get: function () {
  20038. return Camera._PERSPECTIVE_CAMERA;
  20039. },
  20040. enumerable: true,
  20041. configurable: true
  20042. });
  20043. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  20044. get: function () {
  20045. return Camera._ORTHOGRAPHIC_CAMERA;
  20046. },
  20047. enumerable: true,
  20048. configurable: true
  20049. });
  20050. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  20051. /**
  20052. * This is the default FOV mode for perspective cameras.
  20053. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  20054. *
  20055. */
  20056. get: function () {
  20057. return Camera._FOVMODE_VERTICAL_FIXED;
  20058. },
  20059. enumerable: true,
  20060. configurable: true
  20061. });
  20062. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  20063. /**
  20064. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  20065. *
  20066. */
  20067. get: function () {
  20068. return Camera._FOVMODE_HORIZONTAL_FIXED;
  20069. },
  20070. enumerable: true,
  20071. configurable: true
  20072. });
  20073. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  20074. get: function () {
  20075. return Camera._RIG_MODE_NONE;
  20076. },
  20077. enumerable: true,
  20078. configurable: true
  20079. });
  20080. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  20081. get: function () {
  20082. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  20083. },
  20084. enumerable: true,
  20085. configurable: true
  20086. });
  20087. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  20088. get: function () {
  20089. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  20090. },
  20091. enumerable: true,
  20092. configurable: true
  20093. });
  20094. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  20095. get: function () {
  20096. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20097. },
  20098. enumerable: true,
  20099. configurable: true
  20100. });
  20101. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  20102. get: function () {
  20103. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  20104. },
  20105. enumerable: true,
  20106. configurable: true
  20107. });
  20108. Object.defineProperty(Camera, "RIG_MODE_VR", {
  20109. get: function () {
  20110. return Camera._RIG_MODE_VR;
  20111. },
  20112. enumerable: true,
  20113. configurable: true
  20114. });
  20115. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  20116. get: function () {
  20117. return Camera._RIG_MODE_WEBVR;
  20118. },
  20119. enumerable: true,
  20120. configurable: true
  20121. });
  20122. /**
  20123. * Store current camera state (fov, position, etc..)
  20124. */
  20125. Camera.prototype.storeState = function () {
  20126. this._stateStored = true;
  20127. this._storedFov = this.fov;
  20128. return this;
  20129. };
  20130. /**
  20131. * Restores the camera state values if it has been stored. You must call storeState() first
  20132. */
  20133. Camera.prototype._restoreStateValues = function () {
  20134. if (!this._stateStored) {
  20135. return false;
  20136. }
  20137. this.fov = this._storedFov;
  20138. return true;
  20139. };
  20140. /**
  20141. * Restored camera state. You must call storeState() first
  20142. */
  20143. Camera.prototype.restoreState = function () {
  20144. if (this._restoreStateValues()) {
  20145. this.onRestoreStateObservable.notifyObservers(this);
  20146. return true;
  20147. }
  20148. return false;
  20149. };
  20150. Camera.prototype.getClassName = function () {
  20151. return "Camera";
  20152. };
  20153. /**
  20154. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20155. */
  20156. Camera.prototype.toString = function (fullDetails) {
  20157. var ret = "Name: " + this.name;
  20158. ret += ", type: " + this.getClassName();
  20159. if (this.animations) {
  20160. for (var i = 0; i < this.animations.length; i++) {
  20161. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20162. }
  20163. }
  20164. if (fullDetails) {
  20165. }
  20166. return ret;
  20167. };
  20168. Object.defineProperty(Camera.prototype, "globalPosition", {
  20169. get: function () {
  20170. return this._globalPosition;
  20171. },
  20172. enumerable: true,
  20173. configurable: true
  20174. });
  20175. Camera.prototype.getActiveMeshes = function () {
  20176. return this._activeMeshes;
  20177. };
  20178. Camera.prototype.isActiveMesh = function (mesh) {
  20179. return (this._activeMeshes.indexOf(mesh) !== -1);
  20180. };
  20181. //Cache
  20182. Camera.prototype._initCache = function () {
  20183. _super.prototype._initCache.call(this);
  20184. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20185. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20186. this._cache.mode = undefined;
  20187. this._cache.minZ = undefined;
  20188. this._cache.maxZ = undefined;
  20189. this._cache.fov = undefined;
  20190. this._cache.fovMode = undefined;
  20191. this._cache.aspectRatio = undefined;
  20192. this._cache.orthoLeft = undefined;
  20193. this._cache.orthoRight = undefined;
  20194. this._cache.orthoBottom = undefined;
  20195. this._cache.orthoTop = undefined;
  20196. this._cache.renderWidth = undefined;
  20197. this._cache.renderHeight = undefined;
  20198. };
  20199. Camera.prototype._updateCache = function (ignoreParentClass) {
  20200. if (!ignoreParentClass) {
  20201. _super.prototype._updateCache.call(this);
  20202. }
  20203. this._cache.position.copyFrom(this.position);
  20204. this._cache.upVector.copyFrom(this.upVector);
  20205. };
  20206. // Synchronized
  20207. Camera.prototype._isSynchronized = function () {
  20208. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  20209. };
  20210. Camera.prototype._isSynchronizedViewMatrix = function () {
  20211. if (!_super.prototype._isSynchronized.call(this))
  20212. return false;
  20213. return this._cache.position.equals(this.position)
  20214. && this._cache.upVector.equals(this.upVector)
  20215. && this.isSynchronizedWithParent();
  20216. };
  20217. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  20218. var check = this._cache.mode === this.mode
  20219. && this._cache.minZ === this.minZ
  20220. && this._cache.maxZ === this.maxZ;
  20221. if (!check) {
  20222. return false;
  20223. }
  20224. var engine = this.getEngine();
  20225. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20226. check = this._cache.fov === this.fov
  20227. && this._cache.fovMode === this.fovMode
  20228. && this._cache.aspectRatio === engine.getAspectRatio(this);
  20229. }
  20230. else {
  20231. check = this._cache.orthoLeft === this.orthoLeft
  20232. && this._cache.orthoRight === this.orthoRight
  20233. && this._cache.orthoBottom === this.orthoBottom
  20234. && this._cache.orthoTop === this.orthoTop
  20235. && this._cache.renderWidth === engine.getRenderWidth()
  20236. && this._cache.renderHeight === engine.getRenderHeight();
  20237. }
  20238. return check;
  20239. };
  20240. // Controls
  20241. Camera.prototype.attachControl = function (element, noPreventDefault) {
  20242. };
  20243. Camera.prototype.detachControl = function (element) {
  20244. };
  20245. Camera.prototype.update = function () {
  20246. this._checkInputs();
  20247. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20248. this._updateRigCameras();
  20249. }
  20250. };
  20251. Camera.prototype._checkInputs = function () {
  20252. this.onAfterCheckInputsObservable.notifyObservers(this);
  20253. };
  20254. Object.defineProperty(Camera.prototype, "rigCameras", {
  20255. get: function () {
  20256. return this._rigCameras;
  20257. },
  20258. enumerable: true,
  20259. configurable: true
  20260. });
  20261. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  20262. get: function () {
  20263. return this._rigPostProcess;
  20264. },
  20265. enumerable: true,
  20266. configurable: true
  20267. });
  20268. /**
  20269. * Internal, gets the first post proces.
  20270. * @returns the first post process to be run on this camera.
  20271. */
  20272. Camera.prototype._getFirstPostProcess = function () {
  20273. for (var pp in this._postProcesses) {
  20274. if (this._postProcesses[pp] !== null) {
  20275. return this._postProcesses[pp];
  20276. }
  20277. }
  20278. return null;
  20279. };
  20280. Camera.prototype._cascadePostProcessesToRigCams = function () {
  20281. // invalidate framebuffer
  20282. var firstPostProcess = this._getFirstPostProcess();
  20283. if (firstPostProcess) {
  20284. firstPostProcess.markTextureDirty();
  20285. }
  20286. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  20287. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  20288. var cam = this._rigCameras[i];
  20289. var rigPostProcess = cam._rigPostProcess;
  20290. // for VR rig, there does not have to be a post process
  20291. if (rigPostProcess) {
  20292. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20293. if (isPass) {
  20294. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20295. cam.isIntermediate = this._postProcesses.length === 0;
  20296. }
  20297. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20298. rigPostProcess.markTextureDirty();
  20299. }
  20300. else {
  20301. cam._postProcesses = this._postProcesses.slice(0);
  20302. }
  20303. }
  20304. };
  20305. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20306. if (insertAt === void 0) { insertAt = null; }
  20307. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20308. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20309. return 0;
  20310. }
  20311. if (insertAt == null || insertAt < 0) {
  20312. this._postProcesses.push(postProcess);
  20313. }
  20314. else if (this._postProcesses[insertAt] === null) {
  20315. this._postProcesses[insertAt] = postProcess;
  20316. }
  20317. else {
  20318. this._postProcesses.splice(insertAt, 0, postProcess);
  20319. }
  20320. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20321. return this._postProcesses.indexOf(postProcess);
  20322. };
  20323. Camera.prototype.detachPostProcess = function (postProcess) {
  20324. var idx = this._postProcesses.indexOf(postProcess);
  20325. if (idx !== -1) {
  20326. this._postProcesses[idx] = null;
  20327. }
  20328. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20329. };
  20330. Camera.prototype.getWorldMatrix = function () {
  20331. if (!this._worldMatrix) {
  20332. this._worldMatrix = BABYLON.Matrix.Identity();
  20333. }
  20334. var viewMatrix = this.getViewMatrix();
  20335. viewMatrix.invertToRef(this._worldMatrix);
  20336. return this._worldMatrix;
  20337. };
  20338. Camera.prototype._getViewMatrix = function () {
  20339. return BABYLON.Matrix.Identity();
  20340. };
  20341. Camera.prototype.getViewMatrix = function (force) {
  20342. if (!force && this._isSynchronizedViewMatrix()) {
  20343. return this._computedViewMatrix;
  20344. }
  20345. this.updateCache();
  20346. this._computedViewMatrix = this._getViewMatrix();
  20347. this._currentRenderId = this.getScene().getRenderId();
  20348. this._refreshFrustumPlanes = true;
  20349. if (!this.parent || !this.parent.getWorldMatrix) {
  20350. this._globalPosition.copyFrom(this.position);
  20351. }
  20352. else {
  20353. if (!this._worldMatrix) {
  20354. this._worldMatrix = BABYLON.Matrix.Identity();
  20355. }
  20356. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20357. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20358. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20359. this._computedViewMatrix.invert();
  20360. this._markSyncedWithParent();
  20361. }
  20362. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20363. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20364. }
  20365. this.onViewMatrixChangedObservable.notifyObservers(this);
  20366. return this._computedViewMatrix;
  20367. };
  20368. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20369. this._doNotComputeProjectionMatrix = true;
  20370. if (projection !== undefined) {
  20371. this._projectionMatrix = projection;
  20372. }
  20373. };
  20374. ;
  20375. Camera.prototype.unfreezeProjectionMatrix = function () {
  20376. this._doNotComputeProjectionMatrix = false;
  20377. };
  20378. ;
  20379. Camera.prototype.getProjectionMatrix = function (force) {
  20380. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20381. return this._projectionMatrix;
  20382. }
  20383. // Cache
  20384. this._cache.mode = this.mode;
  20385. this._cache.minZ = this.minZ;
  20386. this._cache.maxZ = this.maxZ;
  20387. // Matrix
  20388. this._refreshFrustumPlanes = true;
  20389. var engine = this.getEngine();
  20390. var scene = this.getScene();
  20391. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20392. this._cache.fov = this.fov;
  20393. this._cache.fovMode = this.fovMode;
  20394. this._cache.aspectRatio = engine.getAspectRatio(this);
  20395. if (this.minZ <= 0) {
  20396. this.minZ = 0.1;
  20397. }
  20398. if (scene.useRightHandedSystem) {
  20399. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20400. }
  20401. else {
  20402. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20403. }
  20404. }
  20405. else {
  20406. var halfWidth = engine.getRenderWidth() / 2.0;
  20407. var halfHeight = engine.getRenderHeight() / 2.0;
  20408. if (scene.useRightHandedSystem) {
  20409. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20410. }
  20411. else {
  20412. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20413. }
  20414. this._cache.orthoLeft = this.orthoLeft;
  20415. this._cache.orthoRight = this.orthoRight;
  20416. this._cache.orthoBottom = this.orthoBottom;
  20417. this._cache.orthoTop = this.orthoTop;
  20418. this._cache.renderWidth = engine.getRenderWidth();
  20419. this._cache.renderHeight = engine.getRenderHeight();
  20420. }
  20421. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20422. return this._projectionMatrix;
  20423. };
  20424. Camera.prototype.getTranformationMatrix = function () {
  20425. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20426. return this._transformMatrix;
  20427. };
  20428. Camera.prototype.updateFrustumPlanes = function () {
  20429. if (!this._refreshFrustumPlanes) {
  20430. return;
  20431. }
  20432. this.getTranformationMatrix();
  20433. if (!this._frustumPlanes) {
  20434. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20435. }
  20436. else {
  20437. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20438. }
  20439. this._refreshFrustumPlanes = false;
  20440. };
  20441. Camera.prototype.isInFrustum = function (target) {
  20442. this.updateFrustumPlanes();
  20443. return target.isInFrustum(this._frustumPlanes);
  20444. };
  20445. Camera.prototype.isCompletelyInFrustum = function (target) {
  20446. this.updateFrustumPlanes();
  20447. return target.isCompletelyInFrustum(this._frustumPlanes);
  20448. };
  20449. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20450. if (length === void 0) { length = 100; }
  20451. if (!transform) {
  20452. transform = this.getWorldMatrix();
  20453. }
  20454. if (!origin) {
  20455. origin = this.position;
  20456. }
  20457. var forward = new BABYLON.Vector3(0, 0, 1);
  20458. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20459. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20460. return new BABYLON.Ray(origin, direction, length);
  20461. };
  20462. /**
  20463. * Releases resources associated with this node.
  20464. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20465. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20466. */
  20467. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20468. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20469. // Observables
  20470. this.onViewMatrixChangedObservable.clear();
  20471. this.onProjectionMatrixChangedObservable.clear();
  20472. this.onAfterCheckInputsObservable.clear();
  20473. this.onRestoreStateObservable.clear();
  20474. // Inputs
  20475. if (this.inputs) {
  20476. this.inputs.clear();
  20477. }
  20478. // Animations
  20479. this.getScene().stopAnimation(this);
  20480. // Remove from scene
  20481. this.getScene().removeCamera(this);
  20482. while (this._rigCameras.length > 0) {
  20483. var camera = this._rigCameras.pop();
  20484. if (camera) {
  20485. camera.dispose();
  20486. }
  20487. }
  20488. // Postprocesses
  20489. if (this._rigPostProcess) {
  20490. this._rigPostProcess.dispose(this);
  20491. this._rigPostProcess = null;
  20492. this._postProcesses = [];
  20493. }
  20494. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20495. this._rigPostProcess = null;
  20496. this._postProcesses = [];
  20497. }
  20498. else {
  20499. var i = this._postProcesses.length;
  20500. while (--i >= 0) {
  20501. var postProcess = this._postProcesses[i];
  20502. if (postProcess) {
  20503. postProcess.dispose(this);
  20504. }
  20505. }
  20506. }
  20507. // Render targets
  20508. var i = this.customRenderTargets.length;
  20509. while (--i >= 0) {
  20510. this.customRenderTargets[i].dispose();
  20511. }
  20512. this.customRenderTargets = [];
  20513. // Active Meshes
  20514. this._activeMeshes.dispose();
  20515. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20516. };
  20517. Object.defineProperty(Camera.prototype, "leftCamera", {
  20518. // ---- Camera rigs section ----
  20519. get: function () {
  20520. if (this._rigCameras.length < 1) {
  20521. return null;
  20522. }
  20523. return this._rigCameras[0];
  20524. },
  20525. enumerable: true,
  20526. configurable: true
  20527. });
  20528. Object.defineProperty(Camera.prototype, "rightCamera", {
  20529. get: function () {
  20530. if (this._rigCameras.length < 2) {
  20531. return null;
  20532. }
  20533. return this._rigCameras[1];
  20534. },
  20535. enumerable: true,
  20536. configurable: true
  20537. });
  20538. Camera.prototype.getLeftTarget = function () {
  20539. if (this._rigCameras.length < 1) {
  20540. return null;
  20541. }
  20542. return this._rigCameras[0].getTarget();
  20543. };
  20544. Camera.prototype.getRightTarget = function () {
  20545. if (this._rigCameras.length < 2) {
  20546. return null;
  20547. }
  20548. return this._rigCameras[1].getTarget();
  20549. };
  20550. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20551. if (this.cameraRigMode === mode) {
  20552. return;
  20553. }
  20554. while (this._rigCameras.length > 0) {
  20555. var camera = this._rigCameras.pop();
  20556. if (camera) {
  20557. camera.dispose();
  20558. }
  20559. }
  20560. this.cameraRigMode = mode;
  20561. this._cameraRigParams = {};
  20562. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20563. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20564. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20565. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20566. // create the rig cameras, unless none
  20567. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20568. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20569. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20570. if (leftCamera && rightCamera) {
  20571. this._rigCameras.push(leftCamera);
  20572. this._rigCameras.push(rightCamera);
  20573. }
  20574. }
  20575. switch (this.cameraRigMode) {
  20576. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20577. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20578. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20579. break;
  20580. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20581. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20582. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20583. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20584. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20585. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20586. break;
  20587. case Camera.RIG_MODE_VR:
  20588. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20589. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20590. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20591. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20592. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20593. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20594. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20595. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20596. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20597. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20598. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20599. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20600. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20601. if (metrics.compensateDistortion) {
  20602. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20603. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20604. }
  20605. break;
  20606. case Camera.RIG_MODE_WEBVR:
  20607. if (rigParams.vrDisplay) {
  20608. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20609. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20610. //Left eye
  20611. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20612. this._rigCameras[0].setCameraRigParameter("left", true);
  20613. //leaving this for future reference
  20614. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20615. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20616. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20617. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20618. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20619. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20620. this._rigCameras[0].parent = this;
  20621. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20622. //Right eye
  20623. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20624. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20625. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20626. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20627. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20628. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20629. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20630. this._rigCameras[1].parent = this;
  20631. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20632. if (Camera.UseAlternateWebVRRendering) {
  20633. this._rigCameras[1]._skipRendering = true;
  20634. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20635. }
  20636. }
  20637. break;
  20638. }
  20639. this._cascadePostProcessesToRigCams();
  20640. this.update();
  20641. };
  20642. Camera.prototype._getVRProjectionMatrix = function () {
  20643. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20644. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20645. return this._projectionMatrix;
  20646. };
  20647. Camera.prototype._updateCameraRotationMatrix = function () {
  20648. //Here for WebVR
  20649. };
  20650. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20651. //Here for WebVR
  20652. };
  20653. /**
  20654. * This function MUST be overwritten by the different WebVR cameras available.
  20655. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20656. */
  20657. Camera.prototype._getWebVRProjectionMatrix = function () {
  20658. return BABYLON.Matrix.Identity();
  20659. };
  20660. /**
  20661. * This function MUST be overwritten by the different WebVR cameras available.
  20662. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20663. */
  20664. Camera.prototype._getWebVRViewMatrix = function () {
  20665. return BABYLON.Matrix.Identity();
  20666. };
  20667. Camera.prototype.setCameraRigParameter = function (name, value) {
  20668. if (!this._cameraRigParams) {
  20669. this._cameraRigParams = {};
  20670. }
  20671. this._cameraRigParams[name] = value;
  20672. //provisionnally:
  20673. if (name === "interaxialDistance") {
  20674. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20675. }
  20676. };
  20677. /**
  20678. * needs to be overridden by children so sub has required properties to be copied
  20679. */
  20680. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20681. return null;
  20682. };
  20683. /**
  20684. * May need to be overridden by children
  20685. */
  20686. Camera.prototype._updateRigCameras = function () {
  20687. for (var i = 0; i < this._rigCameras.length; i++) {
  20688. this._rigCameras[i].minZ = this.minZ;
  20689. this._rigCameras[i].maxZ = this.maxZ;
  20690. this._rigCameras[i].fov = this.fov;
  20691. }
  20692. // only update viewport when ANAGLYPH
  20693. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20694. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20695. }
  20696. };
  20697. Camera.prototype._setupInputs = function () {
  20698. };
  20699. Camera.prototype.serialize = function () {
  20700. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20701. // Type
  20702. serializationObject.type = this.getClassName();
  20703. // Parent
  20704. if (this.parent) {
  20705. serializationObject.parentId = this.parent.id;
  20706. }
  20707. if (this.inputs) {
  20708. this.inputs.serialize(serializationObject);
  20709. }
  20710. // Animations
  20711. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20712. serializationObject.ranges = this.serializeAnimationRanges();
  20713. return serializationObject;
  20714. };
  20715. Camera.prototype.clone = function (name) {
  20716. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20717. };
  20718. Camera.prototype.getDirection = function (localAxis) {
  20719. var result = BABYLON.Vector3.Zero();
  20720. this.getDirectionToRef(localAxis, result);
  20721. return result;
  20722. };
  20723. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20724. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20725. };
  20726. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20727. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20728. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20729. switch (type) {
  20730. case "ArcRotateCamera":
  20731. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20732. case "DeviceOrientationCamera":
  20733. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20734. case "FollowCamera":
  20735. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20736. case "ArcFollowCamera":
  20737. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20738. case "GamepadCamera":
  20739. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20740. case "TouchCamera":
  20741. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20742. case "VirtualJoysticksCamera":
  20743. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20744. case "WebVRFreeCamera":
  20745. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20746. case "WebVRGamepadCamera":
  20747. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20748. case "VRDeviceOrientationFreeCamera":
  20749. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20750. case "VRDeviceOrientationGamepadCamera":
  20751. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20752. case "AnaglyphArcRotateCamera":
  20753. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20754. case "AnaglyphFreeCamera":
  20755. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20756. case "AnaglyphGamepadCamera":
  20757. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20758. case "AnaglyphUniversalCamera":
  20759. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20760. case "StereoscopicArcRotateCamera":
  20761. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20762. case "StereoscopicFreeCamera":
  20763. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20764. case "StereoscopicGamepadCamera":
  20765. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20766. case "StereoscopicUniversalCamera":
  20767. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20768. case "FreeCamera":// Forcing Universal here
  20769. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20770. default:// Universal Camera is the default value
  20771. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20772. }
  20773. };
  20774. Camera.prototype.computeWorldMatrix = function () {
  20775. return this.getWorldMatrix();
  20776. };
  20777. Camera.Parse = function (parsedCamera, scene) {
  20778. var type = parsedCamera.type;
  20779. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20780. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20781. // Parent
  20782. if (parsedCamera.parentId) {
  20783. camera._waitingParentId = parsedCamera.parentId;
  20784. }
  20785. //If camera has an input manager, let it parse inputs settings
  20786. if (camera.inputs) {
  20787. camera.inputs.parse(parsedCamera);
  20788. camera._setupInputs();
  20789. }
  20790. if (camera.setPosition) {
  20791. camera.position.copyFromFloats(0, 0, 0);
  20792. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20793. }
  20794. // Target
  20795. if (parsedCamera.target) {
  20796. if (camera.setTarget) {
  20797. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20798. }
  20799. }
  20800. // Apply 3d rig, when found
  20801. if (parsedCamera.cameraRigMode) {
  20802. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20803. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20804. }
  20805. // Animations
  20806. if (parsedCamera.animations) {
  20807. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20808. var parsedAnimation = parsedCamera.animations[animationIndex];
  20809. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20810. }
  20811. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20812. }
  20813. if (parsedCamera.autoAnimate) {
  20814. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20815. }
  20816. return camera;
  20817. };
  20818. // Statics
  20819. Camera._PERSPECTIVE_CAMERA = 0;
  20820. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20821. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20822. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20823. Camera._RIG_MODE_NONE = 0;
  20824. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20825. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20826. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20827. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20828. Camera._RIG_MODE_VR = 20;
  20829. Camera._RIG_MODE_WEBVR = 21;
  20830. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20831. Camera.UseAlternateWebVRRendering = false;
  20832. __decorate([
  20833. BABYLON.serializeAsVector3()
  20834. ], Camera.prototype, "position", void 0);
  20835. __decorate([
  20836. BABYLON.serializeAsVector3()
  20837. ], Camera.prototype, "upVector", void 0);
  20838. __decorate([
  20839. BABYLON.serialize()
  20840. ], Camera.prototype, "orthoLeft", void 0);
  20841. __decorate([
  20842. BABYLON.serialize()
  20843. ], Camera.prototype, "orthoRight", void 0);
  20844. __decorate([
  20845. BABYLON.serialize()
  20846. ], Camera.prototype, "orthoBottom", void 0);
  20847. __decorate([
  20848. BABYLON.serialize()
  20849. ], Camera.prototype, "orthoTop", void 0);
  20850. __decorate([
  20851. BABYLON.serialize()
  20852. ], Camera.prototype, "fov", void 0);
  20853. __decorate([
  20854. BABYLON.serialize()
  20855. ], Camera.prototype, "minZ", void 0);
  20856. __decorate([
  20857. BABYLON.serialize()
  20858. ], Camera.prototype, "maxZ", void 0);
  20859. __decorate([
  20860. BABYLON.serialize()
  20861. ], Camera.prototype, "inertia", void 0);
  20862. __decorate([
  20863. BABYLON.serialize()
  20864. ], Camera.prototype, "mode", void 0);
  20865. __decorate([
  20866. BABYLON.serialize()
  20867. ], Camera.prototype, "layerMask", void 0);
  20868. __decorate([
  20869. BABYLON.serialize()
  20870. ], Camera.prototype, "fovMode", void 0);
  20871. __decorate([
  20872. BABYLON.serialize()
  20873. ], Camera.prototype, "cameraRigMode", void 0);
  20874. __decorate([
  20875. BABYLON.serialize()
  20876. ], Camera.prototype, "interaxialDistance", void 0);
  20877. __decorate([
  20878. BABYLON.serialize()
  20879. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20880. return Camera;
  20881. }(BABYLON.Node));
  20882. BABYLON.Camera = Camera;
  20883. })(BABYLON || (BABYLON = {}));
  20884. //# sourceMappingURL=babylon.camera.js.map
  20885. "use strict";
  20886. var BABYLON;
  20887. (function (BABYLON) {
  20888. var RenderingManager = /** @class */ (function () {
  20889. function RenderingManager(scene) {
  20890. this._renderingGroups = new Array();
  20891. this._autoClearDepthStencil = {};
  20892. this._customOpaqueSortCompareFn = {};
  20893. this._customAlphaTestSortCompareFn = {};
  20894. this._customTransparentSortCompareFn = {};
  20895. this._renderinGroupInfo = null;
  20896. this._scene = scene;
  20897. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20898. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20899. }
  20900. }
  20901. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20902. if (depth === void 0) { depth = true; }
  20903. if (stencil === void 0) { stencil = true; }
  20904. if (this._depthStencilBufferAlreadyCleaned) {
  20905. return;
  20906. }
  20907. this._scene.getEngine().clear(null, false, depth, stencil);
  20908. this._depthStencilBufferAlreadyCleaned = true;
  20909. };
  20910. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20911. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20912. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20913. var info = null;
  20914. if (observable) {
  20915. if (!this._renderinGroupInfo) {
  20916. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20917. }
  20918. info = this._renderinGroupInfo;
  20919. info.scene = this._scene;
  20920. info.camera = this._scene.activeCamera;
  20921. }
  20922. // Dispatch sprites
  20923. if (renderSprites) {
  20924. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20925. var manager = this._scene.spriteManagers[index];
  20926. this.dispatchSprites(manager);
  20927. }
  20928. }
  20929. // Render
  20930. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20931. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20932. var renderingGroup = this._renderingGroups[index];
  20933. if (!renderingGroup && !observable)
  20934. continue;
  20935. var renderingGroupMask = 0;
  20936. // Fire PRECLEAR stage
  20937. if (observable && info) {
  20938. renderingGroupMask = Math.pow(2, index);
  20939. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20940. info.renderingGroupId = index;
  20941. observable.notifyObservers(info, renderingGroupMask);
  20942. }
  20943. // Clear depth/stencil if needed
  20944. if (RenderingManager.AUTOCLEAR) {
  20945. var autoClear = this._autoClearDepthStencil[index];
  20946. if (autoClear && autoClear.autoClear) {
  20947. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20948. }
  20949. }
  20950. if (observable && info) {
  20951. // Fire PREOPAQUE stage
  20952. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20953. observable.notifyObservers(info, renderingGroupMask);
  20954. // Fire PRETRANSPARENT stage
  20955. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20956. observable.notifyObservers(info, renderingGroupMask);
  20957. }
  20958. if (renderingGroup)
  20959. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20960. // Fire POSTTRANSPARENT stage
  20961. if (observable && info) {
  20962. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20963. observable.notifyObservers(info, renderingGroupMask);
  20964. }
  20965. }
  20966. };
  20967. RenderingManager.prototype.reset = function () {
  20968. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20969. var renderingGroup = this._renderingGroups[index];
  20970. if (renderingGroup) {
  20971. renderingGroup.prepare();
  20972. }
  20973. }
  20974. };
  20975. RenderingManager.prototype.dispose = function () {
  20976. this.freeRenderingGroups();
  20977. this._renderingGroups.length = 0;
  20978. };
  20979. /**
  20980. * Clear the info related to rendering groups preventing retention points during dispose.
  20981. */
  20982. RenderingManager.prototype.freeRenderingGroups = function () {
  20983. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20984. var renderingGroup = this._renderingGroups[index];
  20985. if (renderingGroup) {
  20986. renderingGroup.dispose();
  20987. }
  20988. }
  20989. };
  20990. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20991. if (this._renderingGroups[renderingGroupId] === undefined) {
  20992. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20993. }
  20994. };
  20995. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20996. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20997. this._prepareRenderingGroup(renderingGroupId);
  20998. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20999. };
  21000. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  21001. var renderingGroupId = particleSystem.renderingGroupId || 0;
  21002. this._prepareRenderingGroup(renderingGroupId);
  21003. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  21004. };
  21005. /**
  21006. * @param subMesh The submesh to dispatch
  21007. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21008. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21009. */
  21010. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  21011. if (mesh === undefined) {
  21012. mesh = subMesh.getMesh();
  21013. }
  21014. var renderingGroupId = mesh.renderingGroupId || 0;
  21015. this._prepareRenderingGroup(renderingGroupId);
  21016. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  21017. };
  21018. /**
  21019. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  21020. * This allowed control for front to back rendering or reversly depending of the special needs.
  21021. *
  21022. * @param renderingGroupId The rendering group id corresponding to its index
  21023. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21024. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21025. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21026. */
  21027. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21028. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21029. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21030. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21031. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  21032. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  21033. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  21034. if (this._renderingGroups[renderingGroupId]) {
  21035. var group = this._renderingGroups[renderingGroupId];
  21036. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  21037. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  21038. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  21039. }
  21040. };
  21041. /**
  21042. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21043. *
  21044. * @param renderingGroupId The rendering group id corresponding to its index
  21045. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21046. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21047. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21048. */
  21049. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21050. if (depth === void 0) { depth = true; }
  21051. if (stencil === void 0) { stencil = true; }
  21052. this._autoClearDepthStencil[renderingGroupId] = {
  21053. autoClear: autoClearDepthStencil,
  21054. depth: depth,
  21055. stencil: stencil
  21056. };
  21057. };
  21058. /**
  21059. * The max id used for rendering groups (not included)
  21060. */
  21061. RenderingManager.MAX_RENDERINGGROUPS = 4;
  21062. /**
  21063. * The min id used for rendering groups (included)
  21064. */
  21065. RenderingManager.MIN_RENDERINGGROUPS = 0;
  21066. /**
  21067. * Used to globally prevent autoclearing scenes.
  21068. */
  21069. RenderingManager.AUTOCLEAR = true;
  21070. return RenderingManager;
  21071. }());
  21072. BABYLON.RenderingManager = RenderingManager;
  21073. })(BABYLON || (BABYLON = {}));
  21074. //# sourceMappingURL=babylon.renderingManager.js.map
  21075. "use strict";
  21076. var BABYLON;
  21077. (function (BABYLON) {
  21078. var RenderingGroup = /** @class */ (function () {
  21079. /**
  21080. * Creates a new rendering group.
  21081. * @param index The rendering group index
  21082. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  21083. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  21084. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  21085. */
  21086. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21087. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21088. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21089. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21090. this.index = index;
  21091. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  21092. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  21093. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  21094. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  21095. this._particleSystems = new BABYLON.SmartArray(256);
  21096. this._spriteManagers = new BABYLON.SmartArray(256);
  21097. this._edgesRenderers = new BABYLON.SmartArray(16);
  21098. this._scene = scene;
  21099. this.opaqueSortCompareFn = opaqueSortCompareFn;
  21100. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  21101. this.transparentSortCompareFn = transparentSortCompareFn;
  21102. }
  21103. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  21104. /**
  21105. * Set the opaque sort comparison function.
  21106. * If null the sub meshes will be render in the order they were created
  21107. */
  21108. set: function (value) {
  21109. this._opaqueSortCompareFn = value;
  21110. if (value) {
  21111. this._renderOpaque = this.renderOpaqueSorted;
  21112. }
  21113. else {
  21114. this._renderOpaque = RenderingGroup.renderUnsorted;
  21115. }
  21116. },
  21117. enumerable: true,
  21118. configurable: true
  21119. });
  21120. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  21121. /**
  21122. * Set the alpha test sort comparison function.
  21123. * If null the sub meshes will be render in the order they were created
  21124. */
  21125. set: function (value) {
  21126. this._alphaTestSortCompareFn = value;
  21127. if (value) {
  21128. this._renderAlphaTest = this.renderAlphaTestSorted;
  21129. }
  21130. else {
  21131. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  21132. }
  21133. },
  21134. enumerable: true,
  21135. configurable: true
  21136. });
  21137. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  21138. /**
  21139. * Set the transparent sort comparison function.
  21140. * If null the sub meshes will be render in the order they were created
  21141. */
  21142. set: function (value) {
  21143. if (value) {
  21144. this._transparentSortCompareFn = value;
  21145. }
  21146. else {
  21147. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  21148. }
  21149. this._renderTransparent = this.renderTransparentSorted;
  21150. },
  21151. enumerable: true,
  21152. configurable: true
  21153. });
  21154. /**
  21155. * Render all the sub meshes contained in the group.
  21156. * @param customRenderFunction Used to override the default render behaviour of the group.
  21157. * @returns true if rendered some submeshes.
  21158. */
  21159. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  21160. if (customRenderFunction) {
  21161. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  21162. return;
  21163. }
  21164. var engine = this._scene.getEngine();
  21165. // Depth only
  21166. if (this._depthOnlySubMeshes.length !== 0) {
  21167. engine.setColorWrite(false);
  21168. this._renderAlphaTest(this._depthOnlySubMeshes);
  21169. engine.setColorWrite(true);
  21170. }
  21171. // Opaque
  21172. if (this._opaqueSubMeshes.length !== 0) {
  21173. this._renderOpaque(this._opaqueSubMeshes);
  21174. }
  21175. // Alpha test
  21176. if (this._alphaTestSubMeshes.length !== 0) {
  21177. this._renderAlphaTest(this._alphaTestSubMeshes);
  21178. }
  21179. var stencilState = engine.getStencilBuffer();
  21180. engine.setStencilBuffer(false);
  21181. // Sprites
  21182. if (renderSprites) {
  21183. this._renderSprites();
  21184. }
  21185. // Particles
  21186. if (renderParticles) {
  21187. this._renderParticles(activeMeshes);
  21188. }
  21189. if (this.onBeforeTransparentRendering) {
  21190. this.onBeforeTransparentRendering();
  21191. }
  21192. // Transparent
  21193. if (this._transparentSubMeshes.length !== 0) {
  21194. this._renderTransparent(this._transparentSubMeshes);
  21195. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21196. }
  21197. // Set back stencil to false in case it changes before the edge renderer.
  21198. engine.setStencilBuffer(false);
  21199. // Edges
  21200. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  21201. this._edgesRenderers.data[edgesRendererIndex].render();
  21202. }
  21203. // Restore Stencil state.
  21204. engine.setStencilBuffer(stencilState);
  21205. };
  21206. /**
  21207. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  21208. * @param subMeshes The submeshes to render
  21209. */
  21210. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  21211. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  21212. };
  21213. /**
  21214. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  21215. * @param subMeshes The submeshes to render
  21216. */
  21217. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  21218. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  21219. };
  21220. /**
  21221. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  21222. * @param subMeshes The submeshes to render
  21223. */
  21224. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  21225. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  21226. };
  21227. /**
  21228. * Renders the submeshes in a specified order.
  21229. * @param subMeshes The submeshes to sort before render
  21230. * @param sortCompareFn The comparison function use to sort
  21231. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  21232. * @param transparent Specifies to activate blending if true
  21233. */
  21234. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  21235. var subIndex = 0;
  21236. var subMesh;
  21237. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  21238. for (; subIndex < subMeshes.length; subIndex++) {
  21239. subMesh = subMeshes.data[subIndex];
  21240. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  21241. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  21242. }
  21243. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  21244. if (sortCompareFn) {
  21245. sortedArray.sort(sortCompareFn);
  21246. }
  21247. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  21248. subMesh = sortedArray[subIndex];
  21249. if (transparent) {
  21250. var material = subMesh.getMaterial();
  21251. if (material && material.needDepthPrePass) {
  21252. var engine = material.getScene().getEngine();
  21253. engine.setColorWrite(false);
  21254. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21255. subMesh.render(false);
  21256. engine.setColorWrite(true);
  21257. }
  21258. }
  21259. subMesh.render(transparent);
  21260. }
  21261. };
  21262. /**
  21263. * Renders the submeshes in the order they were dispatched (no sort applied).
  21264. * @param subMeshes The submeshes to render
  21265. */
  21266. RenderingGroup.renderUnsorted = function (subMeshes) {
  21267. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  21268. var submesh = subMeshes.data[subIndex];
  21269. submesh.render(false);
  21270. }
  21271. };
  21272. /**
  21273. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21274. * are rendered back to front if in the same alpha index.
  21275. *
  21276. * @param a The first submesh
  21277. * @param b The second submesh
  21278. * @returns The result of the comparison
  21279. */
  21280. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  21281. // Alpha index first
  21282. if (a._alphaIndex > b._alphaIndex) {
  21283. return 1;
  21284. }
  21285. if (a._alphaIndex < b._alphaIndex) {
  21286. return -1;
  21287. }
  21288. // Then distance to camera
  21289. return RenderingGroup.backToFrontSortCompare(a, b);
  21290. };
  21291. /**
  21292. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21293. * are rendered back to front.
  21294. *
  21295. * @param a The first submesh
  21296. * @param b The second submesh
  21297. * @returns The result of the comparison
  21298. */
  21299. RenderingGroup.backToFrontSortCompare = function (a, b) {
  21300. // Then distance to camera
  21301. if (a._distanceToCamera < b._distanceToCamera) {
  21302. return 1;
  21303. }
  21304. if (a._distanceToCamera > b._distanceToCamera) {
  21305. return -1;
  21306. }
  21307. return 0;
  21308. };
  21309. /**
  21310. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21311. * are rendered front to back (prevent overdraw).
  21312. *
  21313. * @param a The first submesh
  21314. * @param b The second submesh
  21315. * @returns The result of the comparison
  21316. */
  21317. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21318. // Then distance to camera
  21319. if (a._distanceToCamera < b._distanceToCamera) {
  21320. return -1;
  21321. }
  21322. if (a._distanceToCamera > b._distanceToCamera) {
  21323. return 1;
  21324. }
  21325. return 0;
  21326. };
  21327. /**
  21328. * Resets the different lists of submeshes to prepare a new frame.
  21329. */
  21330. RenderingGroup.prototype.prepare = function () {
  21331. this._opaqueSubMeshes.reset();
  21332. this._transparentSubMeshes.reset();
  21333. this._alphaTestSubMeshes.reset();
  21334. this._depthOnlySubMeshes.reset();
  21335. this._particleSystems.reset();
  21336. this._spriteManagers.reset();
  21337. this._edgesRenderers.reset();
  21338. };
  21339. RenderingGroup.prototype.dispose = function () {
  21340. this._opaqueSubMeshes.dispose();
  21341. this._transparentSubMeshes.dispose();
  21342. this._alphaTestSubMeshes.dispose();
  21343. this._depthOnlySubMeshes.dispose();
  21344. this._particleSystems.dispose();
  21345. this._spriteManagers.dispose();
  21346. this._edgesRenderers.dispose();
  21347. };
  21348. /**
  21349. * Inserts the submesh in its correct queue depending on its material.
  21350. * @param subMesh The submesh to dispatch
  21351. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21352. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21353. */
  21354. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21355. // Get mesh and materials if not provided
  21356. if (mesh === undefined) {
  21357. mesh = subMesh.getMesh();
  21358. }
  21359. if (material === undefined) {
  21360. material = subMesh.getMaterial();
  21361. }
  21362. if (material === null || material === undefined) {
  21363. return;
  21364. }
  21365. if (material.needAlphaBlendingForMesh(mesh)) {
  21366. this._transparentSubMeshes.push(subMesh);
  21367. }
  21368. else if (material.needAlphaTesting()) {
  21369. if (material.needDepthPrePass) {
  21370. this._depthOnlySubMeshes.push(subMesh);
  21371. }
  21372. this._alphaTestSubMeshes.push(subMesh);
  21373. }
  21374. else {
  21375. if (material.needDepthPrePass) {
  21376. this._depthOnlySubMeshes.push(subMesh);
  21377. }
  21378. this._opaqueSubMeshes.push(subMesh); // Opaque
  21379. }
  21380. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21381. this._edgesRenderers.push(mesh._edgesRenderer);
  21382. }
  21383. };
  21384. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21385. this._spriteManagers.push(spriteManager);
  21386. };
  21387. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21388. this._particleSystems.push(particleSystem);
  21389. };
  21390. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21391. if (this._particleSystems.length === 0) {
  21392. return;
  21393. }
  21394. // Particles
  21395. var activeCamera = this._scene.activeCamera;
  21396. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21397. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21398. var particleSystem = this._particleSystems.data[particleIndex];
  21399. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21400. continue;
  21401. }
  21402. var emitter = particleSystem.emitter;
  21403. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21404. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21405. }
  21406. }
  21407. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21408. };
  21409. RenderingGroup.prototype._renderSprites = function () {
  21410. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21411. return;
  21412. }
  21413. // Sprites
  21414. var activeCamera = this._scene.activeCamera;
  21415. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21416. for (var id = 0; id < this._spriteManagers.length; id++) {
  21417. var spriteManager = this._spriteManagers.data[id];
  21418. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21419. spriteManager.render();
  21420. }
  21421. }
  21422. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21423. };
  21424. return RenderingGroup;
  21425. }());
  21426. BABYLON.RenderingGroup = RenderingGroup;
  21427. })(BABYLON || (BABYLON = {}));
  21428. //# sourceMappingURL=babylon.renderingGroup.js.map
  21429. "use strict";
  21430. var BABYLON;
  21431. (function (BABYLON) {
  21432. var ClickInfo = /** @class */ (function () {
  21433. function ClickInfo() {
  21434. this._singleClick = false;
  21435. this._doubleClick = false;
  21436. this._hasSwiped = false;
  21437. this._ignore = false;
  21438. }
  21439. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21440. get: function () {
  21441. return this._singleClick;
  21442. },
  21443. set: function (b) {
  21444. this._singleClick = b;
  21445. },
  21446. enumerable: true,
  21447. configurable: true
  21448. });
  21449. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21450. get: function () {
  21451. return this._doubleClick;
  21452. },
  21453. set: function (b) {
  21454. this._doubleClick = b;
  21455. },
  21456. enumerable: true,
  21457. configurable: true
  21458. });
  21459. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21460. get: function () {
  21461. return this._hasSwiped;
  21462. },
  21463. set: function (b) {
  21464. this._hasSwiped = b;
  21465. },
  21466. enumerable: true,
  21467. configurable: true
  21468. });
  21469. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21470. get: function () {
  21471. return this._ignore;
  21472. },
  21473. set: function (b) {
  21474. this._ignore = b;
  21475. },
  21476. enumerable: true,
  21477. configurable: true
  21478. });
  21479. return ClickInfo;
  21480. }());
  21481. /**
  21482. * This class is used by the onRenderingGroupObservable
  21483. */
  21484. var RenderingGroupInfo = /** @class */ (function () {
  21485. function RenderingGroupInfo() {
  21486. }
  21487. /**
  21488. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21489. * This stage will be fired no matter what
  21490. */
  21491. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21492. /**
  21493. * Called before opaque object are rendered.
  21494. * This stage will be fired only if there's 3D Opaque content to render
  21495. */
  21496. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21497. /**
  21498. * Called after the opaque objects are rendered and before the transparent ones
  21499. * This stage will be fired only if there's 3D transparent content to render
  21500. */
  21501. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21502. /**
  21503. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21504. * This stage will be fired no matter what
  21505. */
  21506. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21507. return RenderingGroupInfo;
  21508. }());
  21509. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21510. /**
  21511. * Represents a scene to be rendered by the engine.
  21512. * @see http://doc.babylonjs.com/page.php?p=21911
  21513. */
  21514. var Scene = /** @class */ (function () {
  21515. /**
  21516. * @constructor
  21517. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21518. */
  21519. function Scene(engine) {
  21520. // Members
  21521. this.autoClear = true;
  21522. this.autoClearDepthAndStencil = true;
  21523. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21524. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21525. this._forceWireframe = false;
  21526. this._forcePointsCloud = false;
  21527. this.forceShowBoundingBoxes = false;
  21528. this.animationsEnabled = true;
  21529. this.useConstantAnimationDeltaTime = false;
  21530. this.constantlyUpdateMeshUnderPointer = false;
  21531. this.hoverCursor = "pointer";
  21532. this.defaultCursor = "";
  21533. /**
  21534. * This is used to call preventDefault() on pointer down
  21535. * in order to block unwanted artifacts like system double clicks
  21536. */
  21537. this.preventDefaultOnPointerDown = true;
  21538. // Metadata
  21539. this.metadata = null;
  21540. /**
  21541. * An event triggered when the scene is disposed.
  21542. * @type {BABYLON.Observable}
  21543. */
  21544. this.onDisposeObservable = new BABYLON.Observable();
  21545. this._onDisposeObserver = null;
  21546. /**
  21547. * An event triggered before rendering the scene (right after animations and physics)
  21548. * @type {BABYLON.Observable}
  21549. */
  21550. this.onBeforeRenderObservable = new BABYLON.Observable();
  21551. this._onBeforeRenderObserver = null;
  21552. /**
  21553. * An event triggered after rendering the scene
  21554. * @type {BABYLON.Observable}
  21555. */
  21556. this.onAfterRenderObservable = new BABYLON.Observable();
  21557. this._onAfterRenderObserver = null;
  21558. /**
  21559. * An event triggered before animating the scene
  21560. * @type {BABYLON.Observable}
  21561. */
  21562. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21563. /**
  21564. * An event triggered after animations processing
  21565. * @type {BABYLON.Observable}
  21566. */
  21567. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21568. /**
  21569. * An event triggered before draw calls are ready to be sent
  21570. * @type {BABYLON.Observable}
  21571. */
  21572. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21573. /**
  21574. * An event triggered after draw calls have been sent
  21575. * @type {BABYLON.Observable}
  21576. */
  21577. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21578. /**
  21579. * An event triggered when physic simulation is about to be run
  21580. * @type {BABYLON.Observable}
  21581. */
  21582. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21583. /**
  21584. * An event triggered when physic simulation has been done
  21585. * @type {BABYLON.Observable}
  21586. */
  21587. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21588. /**
  21589. * An event triggered when the scene is ready
  21590. * @type {BABYLON.Observable}
  21591. */
  21592. this.onReadyObservable = new BABYLON.Observable();
  21593. /**
  21594. * An event triggered before rendering a camera
  21595. * @type {BABYLON.Observable}
  21596. */
  21597. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21598. this._onBeforeCameraRenderObserver = null;
  21599. /**
  21600. * An event triggered after rendering a camera
  21601. * @type {BABYLON.Observable}
  21602. */
  21603. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21604. this._onAfterCameraRenderObserver = null;
  21605. /**
  21606. * An event triggered when active meshes evaluation is about to start
  21607. * @type {BABYLON.Observable}
  21608. */
  21609. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21610. /**
  21611. * An event triggered when active meshes evaluation is done
  21612. * @type {BABYLON.Observable}
  21613. */
  21614. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21615. /**
  21616. * An event triggered when particles rendering is about to start
  21617. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21618. * @type {BABYLON.Observable}
  21619. */
  21620. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21621. /**
  21622. * An event triggered when particles rendering is done
  21623. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21624. * @type {BABYLON.Observable}
  21625. */
  21626. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21627. /**
  21628. * An event triggered when sprites rendering is about to start
  21629. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21630. * @type {BABYLON.Observable}
  21631. */
  21632. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21633. /**
  21634. * An event triggered when sprites rendering is done
  21635. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21636. * @type {BABYLON.Observable}
  21637. */
  21638. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21639. /**
  21640. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21641. * @type {BABYLON.Observable}
  21642. */
  21643. this.onDataLoadedObservable = new BABYLON.Observable();
  21644. /**
  21645. * An event triggered when a camera is created
  21646. * @type {BABYLON.Observable}
  21647. */
  21648. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21649. /**
  21650. * An event triggered when a camera is removed
  21651. * @type {BABYLON.Observable}
  21652. */
  21653. this.onCameraRemovedObservable = new BABYLON.Observable();
  21654. /**
  21655. * An event triggered when a light is created
  21656. * @type {BABYLON.Observable}
  21657. */
  21658. this.onNewLightAddedObservable = new BABYLON.Observable();
  21659. /**
  21660. * An event triggered when a light is removed
  21661. * @type {BABYLON.Observable}
  21662. */
  21663. this.onLightRemovedObservable = new BABYLON.Observable();
  21664. /**
  21665. * An event triggered when a geometry is created
  21666. * @type {BABYLON.Observable}
  21667. */
  21668. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21669. /**
  21670. * An event triggered when a geometry is removed
  21671. * @type {BABYLON.Observable}
  21672. */
  21673. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21674. /**
  21675. * An event triggered when a transform node is created
  21676. * @type {BABYLON.Observable}
  21677. */
  21678. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21679. /**
  21680. * An event triggered when a transform node is removed
  21681. * @type {BABYLON.Observable}
  21682. */
  21683. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21684. /**
  21685. * An event triggered when a mesh is created
  21686. * @type {BABYLON.Observable}
  21687. */
  21688. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21689. /**
  21690. * An event triggered when a mesh is removed
  21691. * @type {BABYLON.Observable}
  21692. */
  21693. this.onMeshRemovedObservable = new BABYLON.Observable();
  21694. /**
  21695. * An event triggered when render targets are about to be rendered
  21696. * Can happen multiple times per frame.
  21697. * @type {BABYLON.Observable}
  21698. */
  21699. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21700. /**
  21701. * An event triggered when render targets were rendered.
  21702. * Can happen multiple times per frame.
  21703. * @type {BABYLON.Observable}
  21704. */
  21705. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21706. /**
  21707. * An event triggered before calculating deterministic simulation step
  21708. * @type {BABYLON.Observable}
  21709. */
  21710. this.onBeforeStepObservable = new BABYLON.Observable();
  21711. /**
  21712. * An event triggered after calculating deterministic simulation step
  21713. * @type {BABYLON.Observable}
  21714. */
  21715. this.onAfterStepObservable = new BABYLON.Observable();
  21716. /**
  21717. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21718. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21719. * 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)
  21720. */
  21721. this.onRenderingGroupObservable = new BABYLON.Observable();
  21722. // Animations
  21723. this.animations = [];
  21724. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  21725. /**
  21726. * 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).
  21727. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21728. */
  21729. this.onPrePointerObservable = new BABYLON.Observable();
  21730. /**
  21731. * Observable event triggered each time an input event is received from the rendering canvas
  21732. */
  21733. this.onPointerObservable = new BABYLON.Observable();
  21734. this._meshPickProceed = false;
  21735. this._currentPickResult = null;
  21736. this._previousPickResult = null;
  21737. this._totalPointersPressed = 0;
  21738. this._doubleClickOccured = false;
  21739. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21740. this.cameraToUseForPointers = null;
  21741. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21742. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21743. this._startingPointerTime = 0;
  21744. this._previousStartingPointerTime = 0;
  21745. // Deterministic lockstep
  21746. this._timeAccumulator = 0;
  21747. this._currentStepId = 0;
  21748. this._currentInternalStep = 0;
  21749. // Keyboard
  21750. /**
  21751. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21752. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21753. */
  21754. this.onPreKeyboardObservable = new BABYLON.Observable();
  21755. /**
  21756. * Observable event triggered each time an keyboard event is received from the hosting window
  21757. */
  21758. this.onKeyboardObservable = new BABYLON.Observable();
  21759. // Coordinate system
  21760. /**
  21761. * use right-handed coordinate system on this scene.
  21762. * @type {boolean}
  21763. */
  21764. this._useRightHandedSystem = false;
  21765. // Fog
  21766. this._fogEnabled = true;
  21767. this._fogMode = Scene.FOGMODE_NONE;
  21768. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21769. this.fogDensity = 0.1;
  21770. this.fogStart = 0;
  21771. this.fogEnd = 1000.0;
  21772. // Lights
  21773. /**
  21774. * is shadow enabled on this scene.
  21775. * @type {boolean}
  21776. */
  21777. this._shadowsEnabled = true;
  21778. /**
  21779. * is light enabled on this scene.
  21780. * @type {boolean}
  21781. */
  21782. this._lightsEnabled = true;
  21783. /**
  21784. * All of the lights added to this scene.
  21785. * @see BABYLON.Light
  21786. * @type {BABYLON.Light[]}
  21787. */
  21788. this.lights = new Array();
  21789. // Cameras
  21790. /** All of the cameras added to this scene. */
  21791. this.cameras = new Array();
  21792. /** All of the active cameras added to this scene. */
  21793. this.activeCameras = new Array();
  21794. // Meshes
  21795. /**
  21796. * All of the tranform nodes added to this scene.
  21797. * @see BABYLON.TransformNode
  21798. * @type {BABYLON.TransformNode[]}
  21799. */
  21800. this.transformNodes = new Array();
  21801. /**
  21802. * All of the (abstract) meshes added to this scene.
  21803. * @see BABYLON.AbstractMesh
  21804. * @type {BABYLON.AbstractMesh[]}
  21805. */
  21806. this.meshes = new Array();
  21807. /**
  21808. * All of the animation groups added to this scene.
  21809. * @see BABYLON.AnimationGroup
  21810. * @type {BABYLON.AnimationGroup[]}
  21811. */
  21812. this.animationGroups = new Array();
  21813. // Geometries
  21814. this._geometries = new Array();
  21815. this.materials = new Array();
  21816. this.multiMaterials = new Array();
  21817. // Textures
  21818. this._texturesEnabled = true;
  21819. this.textures = new Array();
  21820. // Particles
  21821. this.particlesEnabled = true;
  21822. this.particleSystems = new Array();
  21823. // Sprites
  21824. this.spritesEnabled = true;
  21825. this.spriteManagers = new Array();
  21826. /**
  21827. * The list of layers (background and foreground) of the scene.
  21828. */
  21829. this.layers = new Array();
  21830. /**
  21831. * The list of effect layers (highlights/glow) contained in the scene.
  21832. */
  21833. this.effectLayers = new Array();
  21834. // Skeletons
  21835. this._skeletonsEnabled = true;
  21836. this.skeletons = new Array();
  21837. // Morph targets
  21838. this.morphTargetManagers = new Array();
  21839. // Lens flares
  21840. this.lensFlaresEnabled = true;
  21841. this.lensFlareSystems = new Array();
  21842. // Collisions
  21843. this.collisionsEnabled = true;
  21844. /** Defines the gravity applied to this scene */
  21845. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21846. // Postprocesses
  21847. this.postProcesses = new Array();
  21848. this.postProcessesEnabled = true;
  21849. // Customs render targets
  21850. this.renderTargetsEnabled = true;
  21851. this.dumpNextRenderTargets = false;
  21852. this.customRenderTargets = new Array();
  21853. // Imported meshes
  21854. this.importedMeshesFiles = new Array();
  21855. // Probes
  21856. this.probesEnabled = true;
  21857. this.reflectionProbes = new Array();
  21858. this._actionManagers = new Array();
  21859. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21860. // Procedural textures
  21861. this.proceduralTexturesEnabled = true;
  21862. this._proceduralTextures = new Array();
  21863. this.soundTracks = new Array();
  21864. this._audioEnabled = true;
  21865. this._headphone = false;
  21866. // Performance counters
  21867. this._totalVertices = new BABYLON.PerfCounter();
  21868. this._activeIndices = new BABYLON.PerfCounter();
  21869. this._activeParticles = new BABYLON.PerfCounter();
  21870. this._activeBones = new BABYLON.PerfCounter();
  21871. this._animationTime = 0;
  21872. this.animationTimeScale = 1;
  21873. this._renderId = 0;
  21874. this._executeWhenReadyTimeoutId = -1;
  21875. this._intermediateRendering = false;
  21876. this._viewUpdateFlag = -1;
  21877. this._projectionUpdateFlag = -1;
  21878. this._alternateViewUpdateFlag = -1;
  21879. this._alternateProjectionUpdateFlag = -1;
  21880. this._toBeDisposed = new BABYLON.SmartArray(256);
  21881. this._activeRequests = new Array();
  21882. this._pendingData = new Array();
  21883. this._isDisposed = false;
  21884. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21885. this._activeMeshes = new BABYLON.SmartArray(256);
  21886. this._processedMaterials = new BABYLON.SmartArray(256);
  21887. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21888. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21889. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21890. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21891. this._activeAnimatables = new Array();
  21892. this._transformMatrix = BABYLON.Matrix.Zero();
  21893. this._useAlternateCameraConfiguration = false;
  21894. this._alternateRendering = false;
  21895. this.requireLightSorting = false;
  21896. this._depthRenderer = {};
  21897. this._activeMeshesFrozen = false;
  21898. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21899. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21900. this._engine.scenes.push(this);
  21901. this._uid = null;
  21902. this._renderingManager = new BABYLON.RenderingManager(this);
  21903. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21904. if (BABYLON.OutlineRenderer) {
  21905. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21906. }
  21907. if (BABYLON.Tools.IsWindowObjectExist()) {
  21908. this.attachControl();
  21909. }
  21910. //simplification queue
  21911. if (BABYLON.SimplificationQueue) {
  21912. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21913. }
  21914. //collision coordinator initialization. For now legacy per default.
  21915. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21916. // Uniform Buffer
  21917. this._createUbo();
  21918. // Default Image processing definition.
  21919. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21920. }
  21921. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21922. /** The fog is deactivated */
  21923. get: function () {
  21924. return Scene._FOGMODE_NONE;
  21925. },
  21926. enumerable: true,
  21927. configurable: true
  21928. });
  21929. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21930. /** The fog density is following an exponential function */
  21931. get: function () {
  21932. return Scene._FOGMODE_EXP;
  21933. },
  21934. enumerable: true,
  21935. configurable: true
  21936. });
  21937. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21938. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21939. get: function () {
  21940. return Scene._FOGMODE_EXP2;
  21941. },
  21942. enumerable: true,
  21943. configurable: true
  21944. });
  21945. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21946. /** The fog density is following a linear function. */
  21947. get: function () {
  21948. return Scene._FOGMODE_LINEAR;
  21949. },
  21950. enumerable: true,
  21951. configurable: true
  21952. });
  21953. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21954. /**
  21955. * Texture used in all pbr material as the reflection texture.
  21956. * As in the majority of the scene they are the same (exception for multi room and so on),
  21957. * this is easier to reference from here than from all the materials.
  21958. */
  21959. get: function () {
  21960. return this._environmentTexture;
  21961. },
  21962. /**
  21963. * Texture used in all pbr material as the reflection texture.
  21964. * As in the majority of the scene they are the same (exception for multi room and so on),
  21965. * this is easier to set here than in all the materials.
  21966. */
  21967. set: function (value) {
  21968. if (this._environmentTexture === value) {
  21969. return;
  21970. }
  21971. this._environmentTexture = value;
  21972. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21973. },
  21974. enumerable: true,
  21975. configurable: true
  21976. });
  21977. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21978. /**
  21979. * Default image processing configuration used either in the rendering
  21980. * Forward main pass or through the imageProcessingPostProcess if present.
  21981. * As in the majority of the scene they are the same (exception for multi camera),
  21982. * this is easier to reference from here than from all the materials and post process.
  21983. *
  21984. * No setter as we it is a shared configuration, you can set the values instead.
  21985. */
  21986. get: function () {
  21987. return this._imageProcessingConfiguration;
  21988. },
  21989. enumerable: true,
  21990. configurable: true
  21991. });
  21992. Object.defineProperty(Scene.prototype, "forceWireframe", {
  21993. get: function () {
  21994. return this._forceWireframe;
  21995. },
  21996. set: function (value) {
  21997. if (this._forceWireframe === value) {
  21998. return;
  21999. }
  22000. this._forceWireframe = value;
  22001. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22002. },
  22003. enumerable: true,
  22004. configurable: true
  22005. });
  22006. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  22007. get: function () {
  22008. return this._forcePointsCloud;
  22009. },
  22010. set: function (value) {
  22011. if (this._forcePointsCloud === value) {
  22012. return;
  22013. }
  22014. this._forcePointsCloud = value;
  22015. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22016. },
  22017. enumerable: true,
  22018. configurable: true
  22019. });
  22020. Object.defineProperty(Scene.prototype, "onDispose", {
  22021. /** A function to be executed when this scene is disposed. */
  22022. set: function (callback) {
  22023. if (this._onDisposeObserver) {
  22024. this.onDisposeObservable.remove(this._onDisposeObserver);
  22025. }
  22026. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22027. },
  22028. enumerable: true,
  22029. configurable: true
  22030. });
  22031. Object.defineProperty(Scene.prototype, "beforeRender", {
  22032. /** A function to be executed before rendering this scene */
  22033. set: function (callback) {
  22034. if (this._onBeforeRenderObserver) {
  22035. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  22036. }
  22037. if (callback) {
  22038. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  22039. }
  22040. },
  22041. enumerable: true,
  22042. configurable: true
  22043. });
  22044. Object.defineProperty(Scene.prototype, "afterRender", {
  22045. /** A function to be executed after rendering this scene */
  22046. set: function (callback) {
  22047. if (this._onAfterRenderObserver) {
  22048. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  22049. }
  22050. if (callback) {
  22051. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  22052. }
  22053. },
  22054. enumerable: true,
  22055. configurable: true
  22056. });
  22057. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  22058. set: function (callback) {
  22059. if (this._onBeforeCameraRenderObserver) {
  22060. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  22061. }
  22062. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  22063. },
  22064. enumerable: true,
  22065. configurable: true
  22066. });
  22067. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  22068. set: function (callback) {
  22069. if (this._onAfterCameraRenderObserver) {
  22070. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  22071. }
  22072. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  22073. },
  22074. enumerable: true,
  22075. configurable: true
  22076. });
  22077. Object.defineProperty(Scene.prototype, "gamepadManager", {
  22078. get: function () {
  22079. if (!this._gamepadManager) {
  22080. this._gamepadManager = new BABYLON.GamepadManager(this);
  22081. }
  22082. return this._gamepadManager;
  22083. },
  22084. enumerable: true,
  22085. configurable: true
  22086. });
  22087. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  22088. get: function () {
  22089. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  22090. },
  22091. enumerable: true,
  22092. configurable: true
  22093. });
  22094. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  22095. get: function () {
  22096. return this._useRightHandedSystem;
  22097. },
  22098. set: function (value) {
  22099. if (this._useRightHandedSystem === value) {
  22100. return;
  22101. }
  22102. this._useRightHandedSystem = value;
  22103. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22104. },
  22105. enumerable: true,
  22106. configurable: true
  22107. });
  22108. Scene.prototype.setStepId = function (newStepId) {
  22109. this._currentStepId = newStepId;
  22110. };
  22111. ;
  22112. Scene.prototype.getStepId = function () {
  22113. return this._currentStepId;
  22114. };
  22115. ;
  22116. Scene.prototype.getInternalStep = function () {
  22117. return this._currentInternalStep;
  22118. };
  22119. ;
  22120. Object.defineProperty(Scene.prototype, "fogEnabled", {
  22121. get: function () {
  22122. return this._fogEnabled;
  22123. },
  22124. /**
  22125. * is fog enabled on this scene.
  22126. */
  22127. set: function (value) {
  22128. if (this._fogEnabled === value) {
  22129. return;
  22130. }
  22131. this._fogEnabled = value;
  22132. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22133. },
  22134. enumerable: true,
  22135. configurable: true
  22136. });
  22137. Object.defineProperty(Scene.prototype, "fogMode", {
  22138. get: function () {
  22139. return this._fogMode;
  22140. },
  22141. set: function (value) {
  22142. if (this._fogMode === value) {
  22143. return;
  22144. }
  22145. this._fogMode = value;
  22146. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22147. },
  22148. enumerable: true,
  22149. configurable: true
  22150. });
  22151. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  22152. get: function () {
  22153. return this._shadowsEnabled;
  22154. },
  22155. set: function (value) {
  22156. if (this._shadowsEnabled === value) {
  22157. return;
  22158. }
  22159. this._shadowsEnabled = value;
  22160. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22161. },
  22162. enumerable: true,
  22163. configurable: true
  22164. });
  22165. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  22166. get: function () {
  22167. return this._lightsEnabled;
  22168. },
  22169. set: function (value) {
  22170. if (this._lightsEnabled === value) {
  22171. return;
  22172. }
  22173. this._lightsEnabled = value;
  22174. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22175. },
  22176. enumerable: true,
  22177. configurable: true
  22178. });
  22179. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  22180. /** The default material used on meshes when no material is affected */
  22181. get: function () {
  22182. if (!this._defaultMaterial) {
  22183. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  22184. }
  22185. return this._defaultMaterial;
  22186. },
  22187. /** The default material used on meshes when no material is affected */
  22188. set: function (value) {
  22189. this._defaultMaterial = value;
  22190. },
  22191. enumerable: true,
  22192. configurable: true
  22193. });
  22194. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  22195. get: function () {
  22196. return this._texturesEnabled;
  22197. },
  22198. set: function (value) {
  22199. if (this._texturesEnabled === value) {
  22200. return;
  22201. }
  22202. this._texturesEnabled = value;
  22203. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22204. },
  22205. enumerable: true,
  22206. configurable: true
  22207. });
  22208. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  22209. get: function () {
  22210. return this._skeletonsEnabled;
  22211. },
  22212. set: function (value) {
  22213. if (this._skeletonsEnabled === value) {
  22214. return;
  22215. }
  22216. this._skeletonsEnabled = value;
  22217. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  22218. },
  22219. enumerable: true,
  22220. configurable: true
  22221. });
  22222. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  22223. get: function () {
  22224. if (!this._postProcessRenderPipelineManager) {
  22225. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  22226. }
  22227. return this._postProcessRenderPipelineManager;
  22228. },
  22229. enumerable: true,
  22230. configurable: true
  22231. });
  22232. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  22233. get: function () {
  22234. if (!this._mainSoundTrack) {
  22235. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  22236. }
  22237. return this._mainSoundTrack;
  22238. },
  22239. enumerable: true,
  22240. configurable: true
  22241. });
  22242. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  22243. get: function () {
  22244. return this._alternateRendering;
  22245. },
  22246. enumerable: true,
  22247. configurable: true
  22248. });
  22249. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  22250. get: function () {
  22251. return this._frustumPlanes;
  22252. },
  22253. enumerable: true,
  22254. configurable: true
  22255. });
  22256. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  22257. /**
  22258. * Gets the current geometry buffer associated to the scene.
  22259. */
  22260. get: function () {
  22261. return this._geometryBufferRenderer;
  22262. },
  22263. /**
  22264. * Sets the current geometry buffer for the scene.
  22265. */
  22266. set: function (geometryBufferRenderer) {
  22267. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  22268. this._geometryBufferRenderer = geometryBufferRenderer;
  22269. }
  22270. },
  22271. enumerable: true,
  22272. configurable: true
  22273. });
  22274. Object.defineProperty(Scene.prototype, "debugLayer", {
  22275. // Properties
  22276. get: function () {
  22277. if (!this._debugLayer) {
  22278. this._debugLayer = new BABYLON.DebugLayer(this);
  22279. }
  22280. return this._debugLayer;
  22281. },
  22282. enumerable: true,
  22283. configurable: true
  22284. });
  22285. Object.defineProperty(Scene.prototype, "workerCollisions", {
  22286. get: function () {
  22287. return this._workerCollisions;
  22288. },
  22289. set: function (enabled) {
  22290. if (!BABYLON.CollisionCoordinatorLegacy) {
  22291. return;
  22292. }
  22293. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  22294. this._workerCollisions = enabled;
  22295. if (this.collisionCoordinator) {
  22296. this.collisionCoordinator.destroy();
  22297. }
  22298. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  22299. this.collisionCoordinator.init(this);
  22300. },
  22301. enumerable: true,
  22302. configurable: true
  22303. });
  22304. Object.defineProperty(Scene.prototype, "selectionOctree", {
  22305. get: function () {
  22306. return this._selectionOctree;
  22307. },
  22308. enumerable: true,
  22309. configurable: true
  22310. });
  22311. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  22312. /**
  22313. * The mesh that is currently under the pointer.
  22314. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  22315. */
  22316. get: function () {
  22317. return this._pointerOverMesh;
  22318. },
  22319. enumerable: true,
  22320. configurable: true
  22321. });
  22322. Object.defineProperty(Scene.prototype, "pointerX", {
  22323. /**
  22324. * Current on-screen X position of the pointer
  22325. * @return {number} X position of the pointer
  22326. */
  22327. get: function () {
  22328. return this._pointerX;
  22329. },
  22330. enumerable: true,
  22331. configurable: true
  22332. });
  22333. Object.defineProperty(Scene.prototype, "pointerY", {
  22334. /**
  22335. * Current on-screen Y position of the pointer
  22336. * @return {number} Y position of the pointer
  22337. */
  22338. get: function () {
  22339. return this._pointerY;
  22340. },
  22341. enumerable: true,
  22342. configurable: true
  22343. });
  22344. Scene.prototype.getCachedMaterial = function () {
  22345. return this._cachedMaterial;
  22346. };
  22347. Scene.prototype.getCachedEffect = function () {
  22348. return this._cachedEffect;
  22349. };
  22350. Scene.prototype.getCachedVisibility = function () {
  22351. return this._cachedVisibility;
  22352. };
  22353. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22354. if (visibility === void 0) { visibility = 1; }
  22355. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22356. };
  22357. Scene.prototype.getBoundingBoxRenderer = function () {
  22358. if (!this._boundingBoxRenderer) {
  22359. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22360. }
  22361. return this._boundingBoxRenderer;
  22362. };
  22363. Scene.prototype.getOutlineRenderer = function () {
  22364. return this._outlineRenderer;
  22365. };
  22366. Scene.prototype.getEngine = function () {
  22367. return this._engine;
  22368. };
  22369. Scene.prototype.getTotalVertices = function () {
  22370. return this._totalVertices.current;
  22371. };
  22372. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22373. get: function () {
  22374. return this._totalVertices;
  22375. },
  22376. enumerable: true,
  22377. configurable: true
  22378. });
  22379. Scene.prototype.getActiveIndices = function () {
  22380. return this._activeIndices.current;
  22381. };
  22382. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22383. get: function () {
  22384. return this._activeIndices;
  22385. },
  22386. enumerable: true,
  22387. configurable: true
  22388. });
  22389. Scene.prototype.getActiveParticles = function () {
  22390. return this._activeParticles.current;
  22391. };
  22392. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22393. get: function () {
  22394. return this._activeParticles;
  22395. },
  22396. enumerable: true,
  22397. configurable: true
  22398. });
  22399. Scene.prototype.getActiveBones = function () {
  22400. return this._activeBones.current;
  22401. };
  22402. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22403. get: function () {
  22404. return this._activeBones;
  22405. },
  22406. enumerable: true,
  22407. configurable: true
  22408. });
  22409. // Stats
  22410. Scene.prototype.getInterFramePerfCounter = function () {
  22411. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22412. return 0;
  22413. };
  22414. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22415. get: function () {
  22416. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22417. return null;
  22418. },
  22419. enumerable: true,
  22420. configurable: true
  22421. });
  22422. Scene.prototype.getLastFrameDuration = function () {
  22423. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22424. return 0;
  22425. };
  22426. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22427. get: function () {
  22428. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22429. return null;
  22430. },
  22431. enumerable: true,
  22432. configurable: true
  22433. });
  22434. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22435. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22436. return 0;
  22437. };
  22438. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22439. get: function () {
  22440. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22441. return null;
  22442. },
  22443. enumerable: true,
  22444. configurable: true
  22445. });
  22446. Scene.prototype.getActiveMeshes = function () {
  22447. return this._activeMeshes;
  22448. };
  22449. Scene.prototype.getRenderTargetsDuration = function () {
  22450. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22451. return 0;
  22452. };
  22453. Scene.prototype.getRenderDuration = function () {
  22454. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22455. return 0;
  22456. };
  22457. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22458. get: function () {
  22459. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22460. return null;
  22461. },
  22462. enumerable: true,
  22463. configurable: true
  22464. });
  22465. Scene.prototype.getParticlesDuration = function () {
  22466. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22467. return 0;
  22468. };
  22469. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22470. get: function () {
  22471. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22472. return null;
  22473. },
  22474. enumerable: true,
  22475. configurable: true
  22476. });
  22477. Scene.prototype.getSpritesDuration = function () {
  22478. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22479. return 0;
  22480. };
  22481. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22482. get: function () {
  22483. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22484. return null;
  22485. },
  22486. enumerable: true,
  22487. configurable: true
  22488. });
  22489. Scene.prototype.getAnimationRatio = function () {
  22490. return this._animationRatio;
  22491. };
  22492. Scene.prototype.getRenderId = function () {
  22493. return this._renderId;
  22494. };
  22495. Scene.prototype.incrementRenderId = function () {
  22496. this._renderId++;
  22497. };
  22498. Scene.prototype._updatePointerPosition = function (evt) {
  22499. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22500. if (!canvasRect) {
  22501. return;
  22502. }
  22503. this._pointerX = evt.clientX - canvasRect.left;
  22504. this._pointerY = evt.clientY - canvasRect.top;
  22505. this._unTranslatedPointerX = this._pointerX;
  22506. this._unTranslatedPointerY = this._pointerY;
  22507. };
  22508. Scene.prototype._createUbo = function () {
  22509. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22510. this._sceneUbo.addUniform("viewProjection", 16);
  22511. this._sceneUbo.addUniform("view", 16);
  22512. };
  22513. Scene.prototype._createAlternateUbo = function () {
  22514. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22515. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22516. this._alternateSceneUbo.addUniform("view", 16);
  22517. };
  22518. // Pointers handling
  22519. /**
  22520. * Use this method to simulate a pointer move on a mesh
  22521. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22522. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22523. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22524. */
  22525. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22526. var evt = new PointerEvent("pointermove", pointerEventInit);
  22527. return this._processPointerMove(pickResult, evt);
  22528. };
  22529. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22530. var canvas = this._engine.getRenderingCanvas();
  22531. if (!canvas) {
  22532. return this;
  22533. }
  22534. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22535. this.setPointerOverSprite(null);
  22536. this.setPointerOverMesh(pickResult.pickedMesh);
  22537. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22538. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22539. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22540. }
  22541. else {
  22542. canvas.style.cursor = this.hoverCursor;
  22543. }
  22544. }
  22545. else {
  22546. canvas.style.cursor = this.defaultCursor;
  22547. }
  22548. }
  22549. else {
  22550. this.setPointerOverMesh(null);
  22551. // Sprites
  22552. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22553. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22554. this.setPointerOverSprite(pickResult.pickedSprite);
  22555. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22556. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22557. }
  22558. else {
  22559. canvas.style.cursor = this.hoverCursor;
  22560. }
  22561. }
  22562. else {
  22563. this.setPointerOverSprite(null);
  22564. // Restore pointer
  22565. canvas.style.cursor = this.defaultCursor;
  22566. }
  22567. }
  22568. if (pickResult) {
  22569. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22570. if (this.onPointerMove) {
  22571. this.onPointerMove(evt, pickResult, type);
  22572. }
  22573. if (this.onPointerObservable.hasObservers()) {
  22574. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22575. this.onPointerObservable.notifyObservers(pi, type);
  22576. }
  22577. }
  22578. return this;
  22579. };
  22580. /**
  22581. * Use this method to simulate a pointer down on a mesh
  22582. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22583. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22584. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22585. */
  22586. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22587. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22588. return this._processPointerDown(pickResult, evt);
  22589. };
  22590. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22591. var _this = this;
  22592. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22593. this._pickedDownMesh = pickResult.pickedMesh;
  22594. var actionManager = pickResult.pickedMesh.actionManager;
  22595. if (actionManager) {
  22596. if (actionManager.hasPickTriggers) {
  22597. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22598. switch (evt.button) {
  22599. case 0:
  22600. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22601. break;
  22602. case 1:
  22603. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22604. break;
  22605. case 2:
  22606. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22607. break;
  22608. }
  22609. }
  22610. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22611. window.setTimeout(function () {
  22612. 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);
  22613. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22614. if (_this._totalPointersPressed !== 0 &&
  22615. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22616. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22617. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22618. _this._startingPointerTime = 0;
  22619. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22620. }
  22621. }
  22622. }, Scene.LongPressDelay);
  22623. }
  22624. }
  22625. }
  22626. if (pickResult) {
  22627. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22628. if (this.onPointerDown) {
  22629. this.onPointerDown(evt, pickResult, type);
  22630. }
  22631. if (this.onPointerObservable.hasObservers()) {
  22632. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22633. this.onPointerObservable.notifyObservers(pi, type);
  22634. }
  22635. }
  22636. return this;
  22637. };
  22638. /**
  22639. * Use this method to simulate a pointer up on a mesh
  22640. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22641. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22642. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22643. */
  22644. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22645. var evt = new PointerEvent("pointerup", pointerEventInit);
  22646. var clickInfo = new ClickInfo();
  22647. clickInfo.singleClick = true;
  22648. clickInfo.ignore = true;
  22649. return this._processPointerUp(pickResult, evt, clickInfo);
  22650. };
  22651. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22652. if (pickResult && pickResult && pickResult.pickedMesh) {
  22653. this._pickedUpMesh = pickResult.pickedMesh;
  22654. if (this._pickedDownMesh === this._pickedUpMesh) {
  22655. if (this.onPointerPick) {
  22656. this.onPointerPick(evt, pickResult);
  22657. }
  22658. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22659. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  22660. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  22661. this.onPointerObservable.notifyObservers(pi, type_1);
  22662. }
  22663. }
  22664. if (pickResult.pickedMesh.actionManager) {
  22665. if (clickInfo.ignore) {
  22666. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22667. }
  22668. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22669. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22670. }
  22671. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22672. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22673. }
  22674. }
  22675. }
  22676. if (this._pickedDownMesh &&
  22677. this._pickedDownMesh.actionManager &&
  22678. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22679. this._pickedDownMesh !== this._pickedUpMesh) {
  22680. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22681. }
  22682. var type = BABYLON.PointerEventTypes.POINTERUP;
  22683. if (this.onPointerObservable.hasObservers()) {
  22684. if (!clickInfo.ignore) {
  22685. if (!clickInfo.hasSwiped) {
  22686. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22687. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  22688. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  22689. this.onPointerObservable.notifyObservers(pi, type_2);
  22690. }
  22691. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22692. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22693. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  22694. this.onPointerObservable.notifyObservers(pi, type_3);
  22695. }
  22696. }
  22697. }
  22698. else {
  22699. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22700. this.onPointerObservable.notifyObservers(pi, type);
  22701. }
  22702. }
  22703. if (this.onPointerUp) {
  22704. this.onPointerUp(evt, pickResult, type);
  22705. }
  22706. return this;
  22707. };
  22708. /**
  22709. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22710. * @param attachUp defines if you want to attach events to pointerup
  22711. * @param attachDown defines if you want to attach events to pointerdown
  22712. * @param attachMove defines if you want to attach events to pointermove
  22713. */
  22714. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22715. var _this = this;
  22716. if (attachUp === void 0) { attachUp = true; }
  22717. if (attachDown === void 0) { attachDown = true; }
  22718. if (attachMove === void 0) { attachMove = true; }
  22719. this._initActionManager = function (act, clickInfo) {
  22720. if (!_this._meshPickProceed) {
  22721. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22722. _this._currentPickResult = pickResult;
  22723. if (pickResult) {
  22724. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22725. }
  22726. _this._meshPickProceed = true;
  22727. }
  22728. return act;
  22729. };
  22730. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22731. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22732. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22733. btn !== _this._previousButtonPressed) {
  22734. _this._doubleClickOccured = false;
  22735. clickInfo.singleClick = true;
  22736. clickInfo.ignore = false;
  22737. cb(clickInfo, _this._currentPickResult);
  22738. }
  22739. };
  22740. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22741. var clickInfo = new ClickInfo();
  22742. _this._currentPickResult = null;
  22743. var act = null;
  22744. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22745. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22746. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22747. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22748. act = _this._initActionManager(act, clickInfo);
  22749. if (act)
  22750. checkPicking = act.hasPickTriggers;
  22751. }
  22752. if (checkPicking) {
  22753. var btn = evt.button;
  22754. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22755. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22756. if (!clickInfo.hasSwiped) {
  22757. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22758. if (!checkSingleClickImmediately) {
  22759. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22760. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22761. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22762. act = _this._initActionManager(act, clickInfo);
  22763. if (act)
  22764. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22765. }
  22766. }
  22767. if (checkSingleClickImmediately) {
  22768. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22769. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22770. btn !== _this._previousButtonPressed) {
  22771. clickInfo.singleClick = true;
  22772. cb(clickInfo, _this._currentPickResult);
  22773. }
  22774. }
  22775. else {
  22776. // wait that no double click has been raised during the double click delay
  22777. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22778. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22779. }
  22780. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22781. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22782. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22783. act = _this._initActionManager(act, clickInfo);
  22784. if (act)
  22785. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22786. }
  22787. if (checkDoubleClick) {
  22788. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22789. if (btn === _this._previousButtonPressed &&
  22790. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22791. !_this._doubleClickOccured) {
  22792. // pointer has not moved for 2 clicks, it's a double click
  22793. if (!clickInfo.hasSwiped &&
  22794. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22795. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22796. _this._previousStartingPointerTime = 0;
  22797. _this._doubleClickOccured = true;
  22798. clickInfo.doubleClick = true;
  22799. clickInfo.ignore = false;
  22800. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22801. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22802. }
  22803. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22804. cb(clickInfo, _this._currentPickResult);
  22805. }
  22806. else {
  22807. _this._doubleClickOccured = false;
  22808. _this._previousStartingPointerTime = _this._startingPointerTime;
  22809. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22810. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22811. _this._previousButtonPressed = btn;
  22812. if (Scene.ExclusiveDoubleClickMode) {
  22813. if (_this._previousDelayedSimpleClickTimeout) {
  22814. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22815. }
  22816. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22817. cb(clickInfo, _this._previousPickResult);
  22818. }
  22819. else {
  22820. cb(clickInfo, _this._currentPickResult);
  22821. }
  22822. }
  22823. }
  22824. else {
  22825. _this._doubleClickOccured = false;
  22826. _this._previousStartingPointerTime = _this._startingPointerTime;
  22827. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22828. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22829. _this._previousButtonPressed = btn;
  22830. }
  22831. }
  22832. }
  22833. }
  22834. clickInfo.ignore = true;
  22835. cb(clickInfo, _this._currentPickResult);
  22836. };
  22837. this._spritePredicate = function (sprite) {
  22838. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22839. };
  22840. this._onPointerMove = function (evt) {
  22841. _this._updatePointerPosition(evt);
  22842. // PreObservable support
  22843. if (_this.onPrePointerObservable.hasObservers()) {
  22844. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22845. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22846. _this.onPrePointerObservable.notifyObservers(pi, type);
  22847. if (pi.skipOnPointerObservable) {
  22848. return;
  22849. }
  22850. }
  22851. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22852. return;
  22853. }
  22854. if (!_this.pointerMovePredicate) {
  22855. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22856. }
  22857. // Meshes
  22858. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22859. _this._processPointerMove(pickResult, evt);
  22860. };
  22861. this._onPointerDown = function (evt) {
  22862. _this._totalPointersPressed++;
  22863. _this._pickedDownMesh = null;
  22864. _this._meshPickProceed = false;
  22865. _this._updatePointerPosition(evt);
  22866. if (_this.preventDefaultOnPointerDown && canvas) {
  22867. evt.preventDefault();
  22868. canvas.focus();
  22869. }
  22870. // PreObservable support
  22871. if (_this.onPrePointerObservable.hasObservers()) {
  22872. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22873. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22874. _this.onPrePointerObservable.notifyObservers(pi, type);
  22875. if (pi.skipOnPointerObservable) {
  22876. return;
  22877. }
  22878. }
  22879. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22880. return;
  22881. }
  22882. _this._startingPointerPosition.x = _this._pointerX;
  22883. _this._startingPointerPosition.y = _this._pointerY;
  22884. _this._startingPointerTime = new Date().getTime();
  22885. if (!_this.pointerDownPredicate) {
  22886. _this.pointerDownPredicate = function (mesh) {
  22887. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22888. };
  22889. }
  22890. // Meshes
  22891. _this._pickedDownMesh = null;
  22892. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22893. _this._processPointerDown(pickResult, evt);
  22894. // Sprites
  22895. _this._pickedDownSprite = null;
  22896. if (_this.spriteManagers.length > 0) {
  22897. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22898. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22899. if (pickResult.pickedSprite.actionManager) {
  22900. _this._pickedDownSprite = pickResult.pickedSprite;
  22901. switch (evt.button) {
  22902. case 0:
  22903. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22904. break;
  22905. case 1:
  22906. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22907. break;
  22908. case 2:
  22909. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22910. break;
  22911. }
  22912. if (pickResult.pickedSprite.actionManager) {
  22913. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22914. }
  22915. }
  22916. }
  22917. }
  22918. };
  22919. this._onPointerUp = function (evt) {
  22920. if (_this._totalPointersPressed === 0) {
  22921. return; // So we need to test it the pointer down was pressed before.
  22922. }
  22923. _this._totalPointersPressed--;
  22924. _this._pickedUpMesh = null;
  22925. _this._meshPickProceed = false;
  22926. _this._updatePointerPosition(evt);
  22927. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22928. // PreObservable support
  22929. if (_this.onPrePointerObservable.hasObservers()) {
  22930. if (!clickInfo.ignore) {
  22931. if (!clickInfo.hasSwiped) {
  22932. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22933. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22934. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22935. _this.onPrePointerObservable.notifyObservers(pi, type);
  22936. if (pi.skipOnPointerObservable) {
  22937. return;
  22938. }
  22939. }
  22940. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22941. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22942. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22943. _this.onPrePointerObservable.notifyObservers(pi, type);
  22944. if (pi.skipOnPointerObservable) {
  22945. return;
  22946. }
  22947. }
  22948. }
  22949. }
  22950. else {
  22951. var type = BABYLON.PointerEventTypes.POINTERUP;
  22952. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22953. _this.onPrePointerObservable.notifyObservers(pi, type);
  22954. if (pi.skipOnPointerObservable) {
  22955. return;
  22956. }
  22957. }
  22958. }
  22959. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22960. return;
  22961. }
  22962. if (!_this.pointerUpPredicate) {
  22963. _this.pointerUpPredicate = function (mesh) {
  22964. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22965. };
  22966. }
  22967. // Meshes
  22968. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22969. _this._initActionManager(null, clickInfo);
  22970. }
  22971. if (!pickResult) {
  22972. pickResult = _this._currentPickResult;
  22973. }
  22974. _this._processPointerUp(pickResult, evt, clickInfo);
  22975. // Sprites
  22976. if (_this.spriteManagers.length > 0) {
  22977. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22978. if (spritePickResult) {
  22979. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22980. if (spritePickResult.pickedSprite.actionManager) {
  22981. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22982. if (spritePickResult.pickedSprite.actionManager) {
  22983. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22984. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22985. }
  22986. }
  22987. }
  22988. }
  22989. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22990. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22991. }
  22992. }
  22993. }
  22994. _this._previousPickResult = _this._currentPickResult;
  22995. });
  22996. };
  22997. this._onKeyDown = function (evt) {
  22998. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22999. if (_this.onPreKeyboardObservable.hasObservers()) {
  23000. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23001. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23002. if (pi.skipOnPointerObservable) {
  23003. return;
  23004. }
  23005. }
  23006. if (_this.onKeyboardObservable.hasObservers()) {
  23007. var pi = new BABYLON.KeyboardInfo(type, evt);
  23008. _this.onKeyboardObservable.notifyObservers(pi, type);
  23009. }
  23010. if (_this.actionManager) {
  23011. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23012. }
  23013. };
  23014. this._onKeyUp = function (evt) {
  23015. var type = BABYLON.KeyboardEventTypes.KEYUP;
  23016. if (_this.onPreKeyboardObservable.hasObservers()) {
  23017. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23018. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23019. if (pi.skipOnPointerObservable) {
  23020. return;
  23021. }
  23022. }
  23023. if (_this.onKeyboardObservable.hasObservers()) {
  23024. var pi = new BABYLON.KeyboardInfo(type, evt);
  23025. _this.onKeyboardObservable.notifyObservers(pi, type);
  23026. }
  23027. if (_this.actionManager) {
  23028. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23029. }
  23030. };
  23031. var engine = this.getEngine();
  23032. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  23033. if (!canvas) {
  23034. return;
  23035. }
  23036. canvas.addEventListener("keydown", _this._onKeyDown, false);
  23037. canvas.addEventListener("keyup", _this._onKeyUp, false);
  23038. });
  23039. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  23040. if (!canvas) {
  23041. return;
  23042. }
  23043. canvas.removeEventListener("keydown", _this._onKeyDown);
  23044. canvas.removeEventListener("keyup", _this._onKeyUp);
  23045. });
  23046. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23047. var canvas = this._engine.getRenderingCanvas();
  23048. if (!canvas) {
  23049. return;
  23050. }
  23051. if (attachMove) {
  23052. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  23053. // Wheel
  23054. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  23055. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  23056. }
  23057. if (attachDown) {
  23058. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  23059. }
  23060. if (attachUp) {
  23061. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  23062. }
  23063. canvas.tabIndex = 1;
  23064. };
  23065. Scene.prototype.detachControl = function () {
  23066. var engine = this.getEngine();
  23067. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23068. var canvas = engine.getRenderingCanvas();
  23069. if (!canvas) {
  23070. return;
  23071. }
  23072. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  23073. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  23074. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  23075. if (this._onCanvasBlurObserver) {
  23076. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  23077. }
  23078. if (this._onCanvasFocusObserver) {
  23079. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  23080. }
  23081. // Wheel
  23082. canvas.removeEventListener('mousewheel', this._onPointerMove);
  23083. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  23084. // Keyboard
  23085. canvas.removeEventListener("keydown", this._onKeyDown);
  23086. canvas.removeEventListener("keyup", this._onKeyUp);
  23087. // Observables
  23088. this.onKeyboardObservable.clear();
  23089. this.onPreKeyboardObservable.clear();
  23090. this.onPointerObservable.clear();
  23091. this.onPrePointerObservable.clear();
  23092. };
  23093. /**
  23094. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  23095. * Delay loaded resources are not taking in account
  23096. * @return true if all required resources are ready
  23097. */
  23098. Scene.prototype.isReady = function () {
  23099. if (this._isDisposed) {
  23100. return false;
  23101. }
  23102. if (this._pendingData.length > 0) {
  23103. return false;
  23104. }
  23105. var index;
  23106. var engine = this.getEngine();
  23107. // Geometries
  23108. for (index = 0; index < this._geometries.length; index++) {
  23109. var geometry = this._geometries[index];
  23110. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23111. return false;
  23112. }
  23113. }
  23114. // Meshes
  23115. for (index = 0; index < this.meshes.length; index++) {
  23116. var mesh = this.meshes[index];
  23117. if (!mesh.isEnabled()) {
  23118. continue;
  23119. }
  23120. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  23121. continue;
  23122. }
  23123. if (!mesh.isReady(true)) {
  23124. return false;
  23125. }
  23126. // Effect layers
  23127. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  23128. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  23129. var layer = _a[_i];
  23130. if (!layer.hasMesh(mesh)) {
  23131. continue;
  23132. }
  23133. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  23134. var subMesh = _c[_b];
  23135. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  23136. return false;
  23137. }
  23138. }
  23139. }
  23140. }
  23141. // Particles
  23142. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  23143. var particleSystem = _e[_d];
  23144. if (!particleSystem.isReady()) {
  23145. return false;
  23146. }
  23147. }
  23148. return true;
  23149. };
  23150. Scene.prototype.resetCachedMaterial = function () {
  23151. this._cachedMaterial = null;
  23152. this._cachedEffect = null;
  23153. this._cachedVisibility = null;
  23154. };
  23155. Scene.prototype.registerBeforeRender = function (func) {
  23156. this.onBeforeRenderObservable.add(func);
  23157. };
  23158. Scene.prototype.unregisterBeforeRender = function (func) {
  23159. this.onBeforeRenderObservable.removeCallback(func);
  23160. };
  23161. Scene.prototype.registerAfterRender = function (func) {
  23162. this.onAfterRenderObservable.add(func);
  23163. };
  23164. Scene.prototype.unregisterAfterRender = function (func) {
  23165. this.onAfterRenderObservable.removeCallback(func);
  23166. };
  23167. Scene.prototype._executeOnceBeforeRender = function (func) {
  23168. var _this = this;
  23169. var execFunc = function () {
  23170. func();
  23171. setTimeout(function () {
  23172. _this.unregisterBeforeRender(execFunc);
  23173. });
  23174. };
  23175. this.registerBeforeRender(execFunc);
  23176. };
  23177. /**
  23178. * The provided function will run before render once and will be disposed afterwards.
  23179. * A timeout delay can be provided so that the function will be executed in N ms.
  23180. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  23181. * @param func The function to be executed.
  23182. * @param timeout optional delay in ms
  23183. */
  23184. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  23185. var _this = this;
  23186. if (timeout !== undefined) {
  23187. setTimeout(function () {
  23188. _this._executeOnceBeforeRender(func);
  23189. }, timeout);
  23190. }
  23191. else {
  23192. this._executeOnceBeforeRender(func);
  23193. }
  23194. };
  23195. Scene.prototype._addPendingData = function (data) {
  23196. this._pendingData.push(data);
  23197. };
  23198. Scene.prototype._removePendingData = function (data) {
  23199. var wasLoading = this.isLoading;
  23200. var index = this._pendingData.indexOf(data);
  23201. if (index !== -1) {
  23202. this._pendingData.splice(index, 1);
  23203. }
  23204. if (wasLoading && !this.isLoading) {
  23205. this.onDataLoadedObservable.notifyObservers(this);
  23206. }
  23207. };
  23208. Scene.prototype.getWaitingItemsCount = function () {
  23209. return this._pendingData.length;
  23210. };
  23211. Object.defineProperty(Scene.prototype, "isLoading", {
  23212. get: function () {
  23213. return this._pendingData.length > 0;
  23214. },
  23215. enumerable: true,
  23216. configurable: true
  23217. });
  23218. /**
  23219. * Registers a function to be executed when the scene is ready.
  23220. * @param {Function} func - the function to be executed.
  23221. */
  23222. Scene.prototype.executeWhenReady = function (func) {
  23223. var _this = this;
  23224. this.onReadyObservable.add(func);
  23225. if (this._executeWhenReadyTimeoutId !== -1) {
  23226. return;
  23227. }
  23228. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23229. _this._checkIsReady();
  23230. }, 150);
  23231. };
  23232. /**
  23233. * Returns a promise that resolves when the scene is ready.
  23234. * @returns A promise that resolves when the scene is ready.
  23235. */
  23236. Scene.prototype.whenReadyAsync = function () {
  23237. var _this = this;
  23238. return new Promise(function (resolve) {
  23239. _this.executeWhenReady(function () {
  23240. resolve();
  23241. });
  23242. });
  23243. };
  23244. Scene.prototype._checkIsReady = function () {
  23245. var _this = this;
  23246. if (this.isReady()) {
  23247. this.onReadyObservable.notifyObservers(this);
  23248. this.onReadyObservable.clear();
  23249. this._executeWhenReadyTimeoutId = -1;
  23250. return;
  23251. }
  23252. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23253. _this._checkIsReady();
  23254. }, 150);
  23255. };
  23256. // Animations
  23257. /**
  23258. * Will start the animation sequence of a given target
  23259. * @param target defines the target
  23260. * @param from defines from which frame should animation start
  23261. * @param to defines until which frame should animation run.
  23262. * @param weight defines the weight to apply to the animation (1.0 by default)
  23263. * @param loop defines if the animation loops
  23264. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23265. * @param onAnimationEnd defines the function to be executed when the animation ends
  23266. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23267. * @returns the animatable object created for this animation
  23268. * @see BABYLON.Animatable
  23269. */
  23270. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  23271. if (weight === void 0) { weight = 1.0; }
  23272. if (speedRatio === void 0) { speedRatio = 1.0; }
  23273. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  23274. returnedAnimatable.weight = weight;
  23275. return returnedAnimatable;
  23276. };
  23277. /**
  23278. * Will start the animation sequence of a given target
  23279. * @param target defines the target
  23280. * @param from defines from which frame should animation start
  23281. * @param to defines until which frame should animation run.
  23282. * @param loop defines if the animation loops
  23283. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23284. * @param onAnimationEnd defines the function to be executed when the animation ends
  23285. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23286. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  23287. * @returns the animatable object created for this animation
  23288. * @see BABYLON.Animatable
  23289. */
  23290. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  23291. if (speedRatio === void 0) { speedRatio = 1.0; }
  23292. if (stopCurrent === void 0) { stopCurrent = true; }
  23293. if (from > to && speedRatio > 0) {
  23294. speedRatio *= -1;
  23295. }
  23296. if (stopCurrent) {
  23297. this.stopAnimation(target);
  23298. }
  23299. if (!animatable) {
  23300. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  23301. }
  23302. // Local animations
  23303. if (target.animations) {
  23304. animatable.appendAnimations(target, target.animations);
  23305. }
  23306. // Children animations
  23307. if (target.getAnimatables) {
  23308. var animatables = target.getAnimatables();
  23309. for (var index = 0; index < animatables.length; index++) {
  23310. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  23311. }
  23312. }
  23313. animatable.reset();
  23314. return animatable;
  23315. };
  23316. /**
  23317. * Begin a new animation on a given node
  23318. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23319. * @param {BABYLON.Animation[]} defines the list of animations to start
  23320. * @param {number} from defines the initial value
  23321. * @param {number} to defines the final value
  23322. * @param {boolean} loop defines if you want animation to loop (off by default)
  23323. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23324. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23325. * @returns the list of created animatables
  23326. */
  23327. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23328. if (speedRatio === undefined) {
  23329. speedRatio = 1.0;
  23330. }
  23331. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  23332. return animatable;
  23333. };
  23334. /**
  23335. * Begin a new animation on a given node and its hierarchy
  23336. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23337. * @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.
  23338. * @param {BABYLON.Animation[]} defines the list of animations to start
  23339. * @param {number} from defines the initial value
  23340. * @param {number} to defines the final value
  23341. * @param {boolean} loop defines if you want animation to loop (off by default)
  23342. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23343. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23344. * @returns the list of animatables created for all nodes
  23345. */
  23346. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23347. var children = target.getDescendants(directDescendantsOnly);
  23348. var result = [];
  23349. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  23350. var child = children_1[_i];
  23351. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  23352. }
  23353. return result;
  23354. };
  23355. Scene.prototype.getAnimatableByTarget = function (target) {
  23356. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23357. if (this._activeAnimatables[index].target === target) {
  23358. return this._activeAnimatables[index];
  23359. }
  23360. }
  23361. return null;
  23362. };
  23363. /**
  23364. * Gets all animatables associated with a given target
  23365. * @param target defines the target to look animatables for
  23366. * @returns an array of Animatables
  23367. */
  23368. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  23369. var result = [];
  23370. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23371. if (this._activeAnimatables[index].target === target) {
  23372. result.push(this._activeAnimatables[index]);
  23373. }
  23374. }
  23375. return result;
  23376. };
  23377. Object.defineProperty(Scene.prototype, "animatables", {
  23378. get: function () {
  23379. return this._activeAnimatables;
  23380. },
  23381. enumerable: true,
  23382. configurable: true
  23383. });
  23384. /**
  23385. * Will stop the animation of the given target
  23386. * @param target - the target
  23387. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  23388. * @see beginAnimation
  23389. */
  23390. Scene.prototype.stopAnimation = function (target, animationName) {
  23391. var animatables = this.getAllAnimatablesByTarget(target);
  23392. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  23393. var animatable = animatables_1[_i];
  23394. animatable.stop(animationName);
  23395. }
  23396. };
  23397. /**
  23398. * Stops and removes all animations that have been applied to the scene
  23399. */
  23400. Scene.prototype.stopAllAnimations = function () {
  23401. if (this._activeAnimatables) {
  23402. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23403. this._activeAnimatables[i].stop();
  23404. }
  23405. this._activeAnimatables = [];
  23406. }
  23407. };
  23408. Scene.prototype._animate = function () {
  23409. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23410. return;
  23411. }
  23412. // Getting time
  23413. var now = BABYLON.Tools.Now;
  23414. if (!this._animationTimeLast) {
  23415. if (this._pendingData.length > 0) {
  23416. return;
  23417. }
  23418. this._animationTimeLast = now;
  23419. }
  23420. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23421. this._animationTime += deltaTime;
  23422. this._animationTimeLast = now;
  23423. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23424. this._activeAnimatables[index]._animate(this._animationTime);
  23425. }
  23426. // Late animation bindings
  23427. this._processLateAnimationBindings();
  23428. };
  23429. /** @ignore */
  23430. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  23431. var target = runtimeAnimation.target;
  23432. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  23433. if (!target._lateAnimationHolders) {
  23434. target._lateAnimationHolders = {};
  23435. }
  23436. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  23437. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  23438. totalWeight: 0,
  23439. animations: []
  23440. };
  23441. }
  23442. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  23443. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  23444. };
  23445. Scene.prototype._processLateAnimationBindings = function () {
  23446. if (!this._registeredForLateAnimationBindings.length) {
  23447. return;
  23448. }
  23449. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  23450. var target = this._registeredForLateAnimationBindings.data[index];
  23451. for (var path in target._lateAnimationHolders) {
  23452. var holder = target._lateAnimationHolders[path];
  23453. // Sanity check
  23454. if (!holder.animations[0].originalValue.scaleAndAddToRef) {
  23455. continue;
  23456. }
  23457. var normalizer = 1.0;
  23458. var finalValue = void 0;
  23459. if (holder.totalWeight < 1.0) {
  23460. // We need to mix the original value in
  23461. var originalValue = holder.animations[0].originalValue;
  23462. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  23463. }
  23464. else {
  23465. // We need to normalize the weights
  23466. normalizer = holder.totalWeight;
  23467. }
  23468. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  23469. var runtimeAnimation = holder.animations[animIndex];
  23470. if (finalValue) {
  23471. runtimeAnimation.currentValue.scaleAndAddToRef(runtimeAnimation.weight / normalizer, finalValue);
  23472. }
  23473. else {
  23474. finalValue = runtimeAnimation.currentValue.scale(runtimeAnimation.weight / normalizer);
  23475. }
  23476. }
  23477. runtimeAnimation.target[path] = finalValue;
  23478. }
  23479. target._lateAnimationHolders = {};
  23480. }
  23481. this._registeredForLateAnimationBindings.reset();
  23482. };
  23483. // Matrix
  23484. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23485. this._useAlternateCameraConfiguration = active;
  23486. };
  23487. Scene.prototype.getViewMatrix = function () {
  23488. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23489. };
  23490. Scene.prototype.getProjectionMatrix = function () {
  23491. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23492. };
  23493. Scene.prototype.getTransformMatrix = function () {
  23494. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23495. };
  23496. Scene.prototype.setTransformMatrix = function (view, projection) {
  23497. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23498. return;
  23499. }
  23500. this._viewUpdateFlag = view.updateFlag;
  23501. this._projectionUpdateFlag = projection.updateFlag;
  23502. this._viewMatrix = view;
  23503. this._projectionMatrix = projection;
  23504. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23505. // Update frustum
  23506. if (!this._frustumPlanes) {
  23507. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23508. }
  23509. else {
  23510. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23511. }
  23512. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23513. var otherCamera = this.activeCamera._alternateCamera;
  23514. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23515. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23516. }
  23517. if (this._sceneUbo.useUbo) {
  23518. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23519. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23520. this._sceneUbo.update();
  23521. }
  23522. };
  23523. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23524. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23525. return;
  23526. }
  23527. this._alternateViewUpdateFlag = view.updateFlag;
  23528. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23529. this._alternateViewMatrix = view;
  23530. this._alternateProjectionMatrix = projection;
  23531. if (!this._alternateTransformMatrix) {
  23532. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23533. }
  23534. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23535. if (!this._alternateSceneUbo) {
  23536. this._createAlternateUbo();
  23537. }
  23538. if (this._alternateSceneUbo.useUbo) {
  23539. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23540. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23541. this._alternateSceneUbo.update();
  23542. }
  23543. };
  23544. Scene.prototype.getSceneUniformBuffer = function () {
  23545. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23546. };
  23547. // Methods
  23548. Scene.prototype.getUniqueId = function () {
  23549. var result = Scene._uniqueIdCounter;
  23550. Scene._uniqueIdCounter++;
  23551. return result;
  23552. };
  23553. Scene.prototype.addMesh = function (newMesh) {
  23554. this.meshes.push(newMesh);
  23555. //notify the collision coordinator
  23556. if (this.collisionCoordinator) {
  23557. this.collisionCoordinator.onMeshAdded(newMesh);
  23558. }
  23559. newMesh._resyncLightSources();
  23560. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23561. };
  23562. Scene.prototype.removeMesh = function (toRemove) {
  23563. var index = this.meshes.indexOf(toRemove);
  23564. if (index !== -1) {
  23565. // Remove from the scene if mesh found
  23566. this.meshes.splice(index, 1);
  23567. }
  23568. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23569. return index;
  23570. };
  23571. Scene.prototype.addTransformNode = function (newTransformNode) {
  23572. this.transformNodes.push(newTransformNode);
  23573. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23574. };
  23575. Scene.prototype.removeTransformNode = function (toRemove) {
  23576. var index = this.transformNodes.indexOf(toRemove);
  23577. if (index !== -1) {
  23578. // Remove from the scene if found
  23579. this.transformNodes.splice(index, 1);
  23580. }
  23581. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23582. return index;
  23583. };
  23584. Scene.prototype.removeSkeleton = function (toRemove) {
  23585. var index = this.skeletons.indexOf(toRemove);
  23586. if (index !== -1) {
  23587. // Remove from the scene if found
  23588. this.skeletons.splice(index, 1);
  23589. }
  23590. return index;
  23591. };
  23592. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23593. var index = this.morphTargetManagers.indexOf(toRemove);
  23594. if (index !== -1) {
  23595. // Remove from the scene if found
  23596. this.morphTargetManagers.splice(index, 1);
  23597. }
  23598. return index;
  23599. };
  23600. Scene.prototype.removeLight = function (toRemove) {
  23601. var index = this.lights.indexOf(toRemove);
  23602. if (index !== -1) {
  23603. // Remove from meshes
  23604. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23605. var mesh = _a[_i];
  23606. mesh._removeLightSource(toRemove);
  23607. }
  23608. // Remove from the scene if mesh found
  23609. this.lights.splice(index, 1);
  23610. this.sortLightsByPriority();
  23611. }
  23612. this.onLightRemovedObservable.notifyObservers(toRemove);
  23613. return index;
  23614. };
  23615. Scene.prototype.removeCamera = function (toRemove) {
  23616. var index = this.cameras.indexOf(toRemove);
  23617. if (index !== -1) {
  23618. // Remove from the scene if mesh found
  23619. this.cameras.splice(index, 1);
  23620. }
  23621. // Remove from activeCameras
  23622. var index2 = this.activeCameras.indexOf(toRemove);
  23623. if (index2 !== -1) {
  23624. // Remove from the scene if mesh found
  23625. this.activeCameras.splice(index2, 1);
  23626. }
  23627. // Reset the activeCamera
  23628. if (this.activeCamera === toRemove) {
  23629. if (this.cameras.length > 0) {
  23630. this.activeCamera = this.cameras[0];
  23631. }
  23632. else {
  23633. this.activeCamera = null;
  23634. }
  23635. }
  23636. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23637. return index;
  23638. };
  23639. Scene.prototype.removeParticleSystem = function (toRemove) {
  23640. var index = this.particleSystems.indexOf(toRemove);
  23641. if (index !== -1) {
  23642. this.particleSystems.splice(index, 1);
  23643. }
  23644. return index;
  23645. };
  23646. ;
  23647. Scene.prototype.removeAnimation = function (toRemove) {
  23648. var index = this.animations.indexOf(toRemove);
  23649. if (index !== -1) {
  23650. this.animations.splice(index, 1);
  23651. }
  23652. return index;
  23653. };
  23654. ;
  23655. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23656. var index = this.multiMaterials.indexOf(toRemove);
  23657. if (index !== -1) {
  23658. this.multiMaterials.splice(index, 1);
  23659. }
  23660. return index;
  23661. };
  23662. ;
  23663. Scene.prototype.removeMaterial = function (toRemove) {
  23664. var index = this.materials.indexOf(toRemove);
  23665. if (index !== -1) {
  23666. this.materials.splice(index, 1);
  23667. }
  23668. return index;
  23669. };
  23670. ;
  23671. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23672. var index = this.lensFlareSystems.indexOf(toRemove);
  23673. if (index !== -1) {
  23674. this.lensFlareSystems.splice(index, 1);
  23675. }
  23676. return index;
  23677. };
  23678. ;
  23679. Scene.prototype.removeActionManager = function (toRemove) {
  23680. var index = this._actionManagers.indexOf(toRemove);
  23681. if (index !== -1) {
  23682. this._actionManagers.splice(index, 1);
  23683. }
  23684. return index;
  23685. };
  23686. ;
  23687. Scene.prototype.addLight = function (newLight) {
  23688. this.lights.push(newLight);
  23689. this.sortLightsByPriority();
  23690. // Add light to all meshes (To support if the light is removed and then readded)
  23691. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23692. var mesh = _a[_i];
  23693. if (mesh._lightSources.indexOf(newLight) === -1) {
  23694. mesh._lightSources.push(newLight);
  23695. mesh._resyncLightSources();
  23696. }
  23697. }
  23698. this.onNewLightAddedObservable.notifyObservers(newLight);
  23699. };
  23700. Scene.prototype.sortLightsByPriority = function () {
  23701. if (this.requireLightSorting) {
  23702. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23703. }
  23704. };
  23705. Scene.prototype.addCamera = function (newCamera) {
  23706. this.cameras.push(newCamera);
  23707. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23708. };
  23709. Scene.prototype.addSkeleton = function (newSkeleton) {
  23710. this.skeletons.push(newSkeleton);
  23711. };
  23712. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23713. this.particleSystems.push(newParticleSystem);
  23714. };
  23715. Scene.prototype.addAnimation = function (newAnimation) {
  23716. this.animations.push(newAnimation);
  23717. };
  23718. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23719. this.multiMaterials.push(newMultiMaterial);
  23720. };
  23721. Scene.prototype.addMaterial = function (newMaterial) {
  23722. this.materials.push(newMaterial);
  23723. };
  23724. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23725. this.morphTargetManagers.push(newMorphTargetManager);
  23726. };
  23727. Scene.prototype.addGeometry = function (newGeometrie) {
  23728. this._geometries.push(newGeometrie);
  23729. };
  23730. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23731. this.lensFlareSystems.push(newLensFlareSystem);
  23732. };
  23733. Scene.prototype.addActionManager = function (newActionManager) {
  23734. this._actionManagers.push(newActionManager);
  23735. };
  23736. /**
  23737. * Switch active camera
  23738. * @param {Camera} newCamera - new active camera
  23739. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23740. */
  23741. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23742. if (attachControl === void 0) { attachControl = true; }
  23743. var canvas = this._engine.getRenderingCanvas();
  23744. if (!canvas) {
  23745. return;
  23746. }
  23747. if (this.activeCamera) {
  23748. this.activeCamera.detachControl(canvas);
  23749. }
  23750. this.activeCamera = newCamera;
  23751. if (attachControl) {
  23752. newCamera.attachControl(canvas);
  23753. }
  23754. };
  23755. /**
  23756. * sets the active camera of the scene using its ID
  23757. * @param {string} id - the camera's ID
  23758. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23759. * @see activeCamera
  23760. */
  23761. Scene.prototype.setActiveCameraByID = function (id) {
  23762. var camera = this.getCameraByID(id);
  23763. if (camera) {
  23764. this.activeCamera = camera;
  23765. return camera;
  23766. }
  23767. return null;
  23768. };
  23769. /**
  23770. * sets the active camera of the scene using its name
  23771. * @param {string} name - the camera's name
  23772. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23773. * @see activeCamera
  23774. */
  23775. Scene.prototype.setActiveCameraByName = function (name) {
  23776. var camera = this.getCameraByName(name);
  23777. if (camera) {
  23778. this.activeCamera = camera;
  23779. return camera;
  23780. }
  23781. return null;
  23782. };
  23783. /**
  23784. * get an animation group using its name
  23785. * @param {string} the material's name
  23786. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23787. */
  23788. Scene.prototype.getAnimationGroupByName = function (name) {
  23789. for (var index = 0; index < this.animationGroups.length; index++) {
  23790. if (this.animationGroups[index].name === name) {
  23791. return this.animationGroups[index];
  23792. }
  23793. }
  23794. return null;
  23795. };
  23796. /**
  23797. * get a material using its id
  23798. * @param {string} the material's ID
  23799. * @return {BABYLON.Material|null} the material or null if none found.
  23800. */
  23801. Scene.prototype.getMaterialByID = function (id) {
  23802. for (var index = 0; index < this.materials.length; index++) {
  23803. if (this.materials[index].id === id) {
  23804. return this.materials[index];
  23805. }
  23806. }
  23807. return null;
  23808. };
  23809. /**
  23810. * get a material using its name
  23811. * @param {string} the material's name
  23812. * @return {BABYLON.Material|null} the material or null if none found.
  23813. */
  23814. Scene.prototype.getMaterialByName = function (name) {
  23815. for (var index = 0; index < this.materials.length; index++) {
  23816. if (this.materials[index].name === name) {
  23817. return this.materials[index];
  23818. }
  23819. }
  23820. return null;
  23821. };
  23822. Scene.prototype.getLensFlareSystemByName = function (name) {
  23823. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23824. if (this.lensFlareSystems[index].name === name) {
  23825. return this.lensFlareSystems[index];
  23826. }
  23827. }
  23828. return null;
  23829. };
  23830. Scene.prototype.getLensFlareSystemByID = function (id) {
  23831. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23832. if (this.lensFlareSystems[index].id === id) {
  23833. return this.lensFlareSystems[index];
  23834. }
  23835. }
  23836. return null;
  23837. };
  23838. Scene.prototype.getCameraByID = function (id) {
  23839. for (var index = 0; index < this.cameras.length; index++) {
  23840. if (this.cameras[index].id === id) {
  23841. return this.cameras[index];
  23842. }
  23843. }
  23844. return null;
  23845. };
  23846. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23847. for (var index = 0; index < this.cameras.length; index++) {
  23848. if (this.cameras[index].uniqueId === uniqueId) {
  23849. return this.cameras[index];
  23850. }
  23851. }
  23852. return null;
  23853. };
  23854. /**
  23855. * get a camera using its name
  23856. * @param {string} the camera's name
  23857. * @return {BABYLON.Camera|null} the camera or null if none found.
  23858. */
  23859. Scene.prototype.getCameraByName = function (name) {
  23860. for (var index = 0; index < this.cameras.length; index++) {
  23861. if (this.cameras[index].name === name) {
  23862. return this.cameras[index];
  23863. }
  23864. }
  23865. return null;
  23866. };
  23867. /**
  23868. * get a bone using its id
  23869. * @param {string} the bone's id
  23870. * @return {BABYLON.Bone|null} the bone or null if not found
  23871. */
  23872. Scene.prototype.getBoneByID = function (id) {
  23873. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23874. var skeleton = this.skeletons[skeletonIndex];
  23875. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23876. if (skeleton.bones[boneIndex].id === id) {
  23877. return skeleton.bones[boneIndex];
  23878. }
  23879. }
  23880. }
  23881. return null;
  23882. };
  23883. /**
  23884. * get a bone using its id
  23885. * @param {string} the bone's name
  23886. * @return {BABYLON.Bone|null} the bone or null if not found
  23887. */
  23888. Scene.prototype.getBoneByName = function (name) {
  23889. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23890. var skeleton = this.skeletons[skeletonIndex];
  23891. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23892. if (skeleton.bones[boneIndex].name === name) {
  23893. return skeleton.bones[boneIndex];
  23894. }
  23895. }
  23896. }
  23897. return null;
  23898. };
  23899. /**
  23900. * get a light node using its name
  23901. * @param {string} the light's name
  23902. * @return {BABYLON.Light|null} the light or null if none found.
  23903. */
  23904. Scene.prototype.getLightByName = function (name) {
  23905. for (var index = 0; index < this.lights.length; index++) {
  23906. if (this.lights[index].name === name) {
  23907. return this.lights[index];
  23908. }
  23909. }
  23910. return null;
  23911. };
  23912. /**
  23913. * get a light node using its ID
  23914. * @param {string} the light's id
  23915. * @return {BABYLON.Light|null} the light or null if none found.
  23916. */
  23917. Scene.prototype.getLightByID = function (id) {
  23918. for (var index = 0; index < this.lights.length; index++) {
  23919. if (this.lights[index].id === id) {
  23920. return this.lights[index];
  23921. }
  23922. }
  23923. return null;
  23924. };
  23925. /**
  23926. * get a light node using its scene-generated unique ID
  23927. * @param {number} the light's unique id
  23928. * @return {BABYLON.Light|null} the light or null if none found.
  23929. */
  23930. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23931. for (var index = 0; index < this.lights.length; index++) {
  23932. if (this.lights[index].uniqueId === uniqueId) {
  23933. return this.lights[index];
  23934. }
  23935. }
  23936. return null;
  23937. };
  23938. /**
  23939. * get a particle system by id
  23940. * @param id {number} the particle system id
  23941. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23942. */
  23943. Scene.prototype.getParticleSystemByID = function (id) {
  23944. for (var index = 0; index < this.particleSystems.length; index++) {
  23945. if (this.particleSystems[index].id === id) {
  23946. return this.particleSystems[index];
  23947. }
  23948. }
  23949. return null;
  23950. };
  23951. /**
  23952. * get a geometry using its ID
  23953. * @param {string} the geometry's id
  23954. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23955. */
  23956. Scene.prototype.getGeometryByID = function (id) {
  23957. for (var index = 0; index < this._geometries.length; index++) {
  23958. if (this._geometries[index].id === id) {
  23959. return this._geometries[index];
  23960. }
  23961. }
  23962. return null;
  23963. };
  23964. /**
  23965. * add a new geometry to this scene.
  23966. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23967. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23968. * @return {boolean} was the geometry added or not
  23969. */
  23970. Scene.prototype.pushGeometry = function (geometry, force) {
  23971. if (!force && this.getGeometryByID(geometry.id)) {
  23972. return false;
  23973. }
  23974. this._geometries.push(geometry);
  23975. //notify the collision coordinator
  23976. if (this.collisionCoordinator) {
  23977. this.collisionCoordinator.onGeometryAdded(geometry);
  23978. }
  23979. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23980. return true;
  23981. };
  23982. /**
  23983. * Removes an existing geometry
  23984. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23985. * @return {boolean} was the geometry removed or not
  23986. */
  23987. Scene.prototype.removeGeometry = function (geometry) {
  23988. var index = this._geometries.indexOf(geometry);
  23989. if (index > -1) {
  23990. this._geometries.splice(index, 1);
  23991. //notify the collision coordinator
  23992. if (this.collisionCoordinator) {
  23993. this.collisionCoordinator.onGeometryDeleted(geometry);
  23994. }
  23995. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23996. return true;
  23997. }
  23998. return false;
  23999. };
  24000. Scene.prototype.getGeometries = function () {
  24001. return this._geometries;
  24002. };
  24003. /**
  24004. * Get the first added mesh found of a given ID
  24005. * @param {string} id - the id to search for
  24006. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24007. */
  24008. Scene.prototype.getMeshByID = function (id) {
  24009. for (var index = 0; index < this.meshes.length; index++) {
  24010. if (this.meshes[index].id === id) {
  24011. return this.meshes[index];
  24012. }
  24013. }
  24014. return null;
  24015. };
  24016. Scene.prototype.getMeshesByID = function (id) {
  24017. return this.meshes.filter(function (m) {
  24018. return m.id === id;
  24019. });
  24020. };
  24021. /**
  24022. * Get the first added transform node found of a given ID
  24023. * @param {string} id - the id to search for
  24024. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  24025. */
  24026. Scene.prototype.getTransformNodeByID = function (id) {
  24027. for (var index = 0; index < this.transformNodes.length; index++) {
  24028. if (this.transformNodes[index].id === id) {
  24029. return this.transformNodes[index];
  24030. }
  24031. }
  24032. return null;
  24033. };
  24034. Scene.prototype.getTransformNodesByID = function (id) {
  24035. return this.transformNodes.filter(function (m) {
  24036. return m.id === id;
  24037. });
  24038. };
  24039. /**
  24040. * Get a mesh with its auto-generated unique id
  24041. * @param {number} uniqueId - the unique id to search for
  24042. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24043. */
  24044. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  24045. for (var index = 0; index < this.meshes.length; index++) {
  24046. if (this.meshes[index].uniqueId === uniqueId) {
  24047. return this.meshes[index];
  24048. }
  24049. }
  24050. return null;
  24051. };
  24052. /**
  24053. * Get a the last added mesh found of a given ID
  24054. * @param {string} id - the id to search for
  24055. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24056. */
  24057. Scene.prototype.getLastMeshByID = function (id) {
  24058. for (var index = this.meshes.length - 1; index >= 0; index--) {
  24059. if (this.meshes[index].id === id) {
  24060. return this.meshes[index];
  24061. }
  24062. }
  24063. return null;
  24064. };
  24065. /**
  24066. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  24067. * @param {string} id - the id to search for
  24068. * @return {BABYLON.Node|null} the node found or null if not found at all.
  24069. */
  24070. Scene.prototype.getLastEntryByID = function (id) {
  24071. var index;
  24072. for (index = this.meshes.length - 1; index >= 0; index--) {
  24073. if (this.meshes[index].id === id) {
  24074. return this.meshes[index];
  24075. }
  24076. }
  24077. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  24078. if (this.transformNodes[index].id === id) {
  24079. return this.transformNodes[index];
  24080. }
  24081. }
  24082. for (index = this.cameras.length - 1; index >= 0; index--) {
  24083. if (this.cameras[index].id === id) {
  24084. return this.cameras[index];
  24085. }
  24086. }
  24087. for (index = this.lights.length - 1; index >= 0; index--) {
  24088. if (this.lights[index].id === id) {
  24089. return this.lights[index];
  24090. }
  24091. }
  24092. return null;
  24093. };
  24094. Scene.prototype.getNodeByID = function (id) {
  24095. var mesh = this.getMeshByID(id);
  24096. if (mesh) {
  24097. return mesh;
  24098. }
  24099. var light = this.getLightByID(id);
  24100. if (light) {
  24101. return light;
  24102. }
  24103. var camera = this.getCameraByID(id);
  24104. if (camera) {
  24105. return camera;
  24106. }
  24107. var bone = this.getBoneByID(id);
  24108. return bone;
  24109. };
  24110. Scene.prototype.getNodeByName = function (name) {
  24111. var mesh = this.getMeshByName(name);
  24112. if (mesh) {
  24113. return mesh;
  24114. }
  24115. var light = this.getLightByName(name);
  24116. if (light) {
  24117. return light;
  24118. }
  24119. var camera = this.getCameraByName(name);
  24120. if (camera) {
  24121. return camera;
  24122. }
  24123. var bone = this.getBoneByName(name);
  24124. return bone;
  24125. };
  24126. Scene.prototype.getMeshByName = function (name) {
  24127. for (var index = 0; index < this.meshes.length; index++) {
  24128. if (this.meshes[index].name === name) {
  24129. return this.meshes[index];
  24130. }
  24131. }
  24132. return null;
  24133. };
  24134. Scene.prototype.getTransformNodeByName = function (name) {
  24135. for (var index = 0; index < this.transformNodes.length; index++) {
  24136. if (this.transformNodes[index].name === name) {
  24137. return this.transformNodes[index];
  24138. }
  24139. }
  24140. return null;
  24141. };
  24142. Scene.prototype.getSoundByName = function (name) {
  24143. var index;
  24144. if (BABYLON.AudioEngine) {
  24145. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  24146. if (this.mainSoundTrack.soundCollection[index].name === name) {
  24147. return this.mainSoundTrack.soundCollection[index];
  24148. }
  24149. }
  24150. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  24151. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  24152. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  24153. return this.soundTracks[sdIndex].soundCollection[index];
  24154. }
  24155. }
  24156. }
  24157. }
  24158. return null;
  24159. };
  24160. Scene.prototype.getLastSkeletonByID = function (id) {
  24161. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  24162. if (this.skeletons[index].id === id) {
  24163. return this.skeletons[index];
  24164. }
  24165. }
  24166. return null;
  24167. };
  24168. Scene.prototype.getSkeletonById = function (id) {
  24169. for (var index = 0; index < this.skeletons.length; index++) {
  24170. if (this.skeletons[index].id === id) {
  24171. return this.skeletons[index];
  24172. }
  24173. }
  24174. return null;
  24175. };
  24176. Scene.prototype.getSkeletonByName = function (name) {
  24177. for (var index = 0; index < this.skeletons.length; index++) {
  24178. if (this.skeletons[index].name === name) {
  24179. return this.skeletons[index];
  24180. }
  24181. }
  24182. return null;
  24183. };
  24184. Scene.prototype.getMorphTargetManagerById = function (id) {
  24185. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  24186. if (this.morphTargetManagers[index].uniqueId === id) {
  24187. return this.morphTargetManagers[index];
  24188. }
  24189. }
  24190. return null;
  24191. };
  24192. Scene.prototype.isActiveMesh = function (mesh) {
  24193. return (this._activeMeshes.indexOf(mesh) !== -1);
  24194. };
  24195. /**
  24196. * Return a the first highlight layer of the scene with a given name.
  24197. * @param name The name of the highlight layer to look for.
  24198. * @return The highlight layer if found otherwise null.
  24199. */
  24200. Scene.prototype.getHighlightLayerByName = function (name) {
  24201. for (var index = 0; index < this.effectLayers.length; index++) {
  24202. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  24203. return this.effectLayers[index];
  24204. }
  24205. }
  24206. return null;
  24207. };
  24208. /**
  24209. * Return a the first highlight layer of the scene with a given name.
  24210. * @param name The name of the highlight layer to look for.
  24211. * @return The highlight layer if found otherwise null.
  24212. */
  24213. Scene.prototype.getGlowLayerByName = function (name) {
  24214. for (var index = 0; index < this.effectLayers.length; index++) {
  24215. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  24216. return this.effectLayers[index];
  24217. }
  24218. }
  24219. return null;
  24220. };
  24221. Object.defineProperty(Scene.prototype, "uid", {
  24222. /**
  24223. * Return a unique id as a string which can serve as an identifier for the scene
  24224. */
  24225. get: function () {
  24226. if (!this._uid) {
  24227. this._uid = BABYLON.Tools.RandomId();
  24228. }
  24229. return this._uid;
  24230. },
  24231. enumerable: true,
  24232. configurable: true
  24233. });
  24234. /**
  24235. * Add an externaly attached data from its key.
  24236. * This method call will fail and return false, if such key already exists.
  24237. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  24238. * @param key the unique key that identifies the data
  24239. * @param data the data object to associate to the key for this Engine instance
  24240. * @return true if no such key were already present and the data was added successfully, false otherwise
  24241. */
  24242. Scene.prototype.addExternalData = function (key, data) {
  24243. if (!this._externalData) {
  24244. this._externalData = new BABYLON.StringDictionary();
  24245. }
  24246. return this._externalData.add(key, data);
  24247. };
  24248. /**
  24249. * Get an externaly attached data from its key
  24250. * @param key the unique key that identifies the data
  24251. * @return the associated data, if present (can be null), or undefined if not present
  24252. */
  24253. Scene.prototype.getExternalData = function (key) {
  24254. if (!this._externalData) {
  24255. return null;
  24256. }
  24257. return this._externalData.get(key);
  24258. };
  24259. /**
  24260. * Get an externaly attached data from its key, create it using a factory if it's not already present
  24261. * @param key the unique key that identifies the data
  24262. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  24263. * @return the associated data, can be null if the factory returned null.
  24264. */
  24265. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  24266. if (!this._externalData) {
  24267. this._externalData = new BABYLON.StringDictionary();
  24268. }
  24269. return this._externalData.getOrAddWithFactory(key, factory);
  24270. };
  24271. /**
  24272. * Remove an externaly attached data from the Engine instance
  24273. * @param key the unique key that identifies the data
  24274. * @return true if the data was successfully removed, false if it doesn't exist
  24275. */
  24276. Scene.prototype.removeExternalData = function (key) {
  24277. return this._externalData.remove(key);
  24278. };
  24279. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  24280. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  24281. if (mesh.showSubMeshesBoundingBox) {
  24282. var boundingInfo = subMesh.getBoundingInfo();
  24283. if (boundingInfo !== null && boundingInfo !== undefined) {
  24284. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24285. }
  24286. }
  24287. var material = subMesh.getMaterial();
  24288. if (material !== null && material !== undefined) {
  24289. // Render targets
  24290. if (material.getRenderTargetTextures !== undefined) {
  24291. if (this._processedMaterials.indexOf(material) === -1) {
  24292. this._processedMaterials.push(material);
  24293. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  24294. }
  24295. }
  24296. // Dispatch
  24297. this._activeIndices.addCount(subMesh.indexCount, false);
  24298. this._renderingManager.dispatch(subMesh, mesh, material);
  24299. }
  24300. }
  24301. };
  24302. /**
  24303. * Clear the processed materials smart array preventing retention point in material dispose.
  24304. */
  24305. Scene.prototype.freeProcessedMaterials = function () {
  24306. this._processedMaterials.dispose();
  24307. };
  24308. /**
  24309. * Clear the active meshes smart array preventing retention point in mesh dispose.
  24310. */
  24311. Scene.prototype.freeActiveMeshes = function () {
  24312. this._activeMeshes.dispose();
  24313. if (this.activeCamera && this.activeCamera._activeMeshes) {
  24314. this.activeCamera._activeMeshes.dispose();
  24315. }
  24316. if (this.activeCameras) {
  24317. for (var i = 0; i < this.activeCameras.length; i++) {
  24318. var activeCamera = this.activeCameras[i];
  24319. if (activeCamera && activeCamera._activeMeshes) {
  24320. activeCamera._activeMeshes.dispose();
  24321. }
  24322. }
  24323. }
  24324. };
  24325. /**
  24326. * Clear the info related to rendering groups preventing retention points during dispose.
  24327. */
  24328. Scene.prototype.freeRenderingGroups = function () {
  24329. if (this._renderingManager) {
  24330. this._renderingManager.freeRenderingGroups();
  24331. }
  24332. if (this.textures) {
  24333. for (var i = 0; i < this.textures.length; i++) {
  24334. var texture = this.textures[i];
  24335. if (texture && texture.renderList) {
  24336. texture.freeRenderingGroups();
  24337. }
  24338. }
  24339. }
  24340. };
  24341. Scene.prototype._isInIntermediateRendering = function () {
  24342. return this._intermediateRendering;
  24343. };
  24344. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  24345. this._activeMeshCandidateProvider = provider;
  24346. };
  24347. Scene.prototype.getActiveMeshCandidateProvider = function () {
  24348. return this._activeMeshCandidateProvider;
  24349. };
  24350. /**
  24351. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  24352. */
  24353. Scene.prototype.freezeActiveMeshes = function () {
  24354. if (!this.activeCamera) {
  24355. return this;
  24356. }
  24357. if (!this._frustumPlanes) {
  24358. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24359. }
  24360. this._evaluateActiveMeshes();
  24361. this._activeMeshesFrozen = true;
  24362. return this;
  24363. };
  24364. /**
  24365. * Use this function to restart evaluating active meshes on every frame
  24366. */
  24367. Scene.prototype.unfreezeActiveMeshes = function () {
  24368. this._activeMeshesFrozen = false;
  24369. return this;
  24370. };
  24371. Scene.prototype._evaluateActiveMeshes = function () {
  24372. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  24373. return;
  24374. }
  24375. if (!this.activeCamera) {
  24376. return;
  24377. }
  24378. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  24379. this.activeCamera._activeMeshes.reset();
  24380. this._activeMeshes.reset();
  24381. this._renderingManager.reset();
  24382. this._processedMaterials.reset();
  24383. this._activeParticleSystems.reset();
  24384. this._activeSkeletons.reset();
  24385. this._softwareSkinnedMeshes.reset();
  24386. if (this._boundingBoxRenderer) {
  24387. this._boundingBoxRenderer.reset();
  24388. }
  24389. // Meshes
  24390. var meshes;
  24391. var len;
  24392. var checkIsEnabled = true;
  24393. // Determine mesh candidates
  24394. if (this._activeMeshCandidateProvider !== undefined) {
  24395. // Use _activeMeshCandidateProvider
  24396. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  24397. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  24398. if (meshes !== undefined) {
  24399. len = meshes.length;
  24400. }
  24401. else {
  24402. len = 0;
  24403. }
  24404. }
  24405. else if (this._selectionOctree !== undefined) {
  24406. // Octree
  24407. var selection = this._selectionOctree.select(this._frustumPlanes);
  24408. meshes = selection.data;
  24409. len = selection.length;
  24410. }
  24411. else {
  24412. // Full scene traversal
  24413. len = this.meshes.length;
  24414. meshes = this.meshes;
  24415. }
  24416. // Check each mesh
  24417. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  24418. mesh = meshes[meshIndex];
  24419. if (mesh.isBlocked) {
  24420. continue;
  24421. }
  24422. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  24423. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  24424. continue;
  24425. }
  24426. mesh.computeWorldMatrix();
  24427. // Intersections
  24428. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  24429. this._meshesForIntersections.pushNoDuplicate(mesh);
  24430. }
  24431. // Switch to current LOD
  24432. meshLOD = mesh.getLOD(this.activeCamera);
  24433. if (meshLOD === undefined || meshLOD === null) {
  24434. continue;
  24435. }
  24436. mesh._preActivate();
  24437. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  24438. this._activeMeshes.push(mesh);
  24439. this.activeCamera._activeMeshes.push(mesh);
  24440. mesh._activate(this._renderId);
  24441. if (meshLOD !== mesh) {
  24442. meshLOD._activate(this._renderId);
  24443. }
  24444. this._activeMesh(mesh, meshLOD);
  24445. }
  24446. }
  24447. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  24448. // Particle systems
  24449. if (this.particlesEnabled) {
  24450. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  24451. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  24452. var particleSystem = this.particleSystems[particleIndex];
  24453. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  24454. continue;
  24455. }
  24456. var emitter = particleSystem.emitter;
  24457. if (!emitter.position || emitter.isEnabled()) {
  24458. this._activeParticleSystems.push(particleSystem);
  24459. particleSystem.animate();
  24460. this._renderingManager.dispatchParticles(particleSystem);
  24461. }
  24462. }
  24463. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  24464. }
  24465. };
  24466. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  24467. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  24468. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  24469. mesh.skeleton.prepare();
  24470. }
  24471. if (!mesh.computeBonesUsingShaders) {
  24472. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  24473. }
  24474. }
  24475. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  24476. var boundingInfo = sourceMesh.getBoundingInfo();
  24477. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24478. }
  24479. if (mesh !== undefined && mesh !== null
  24480. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  24481. // Submeshes Octrees
  24482. var len;
  24483. var subMeshes;
  24484. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  24485. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  24486. len = intersections.length;
  24487. subMeshes = intersections.data;
  24488. }
  24489. else {
  24490. subMeshes = mesh.subMeshes;
  24491. len = subMeshes.length;
  24492. }
  24493. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  24494. subMesh = subMeshes[subIndex];
  24495. this._evaluateSubMesh(subMesh, mesh);
  24496. }
  24497. }
  24498. };
  24499. Scene.prototype.updateTransformMatrix = function (force) {
  24500. if (!this.activeCamera) {
  24501. return;
  24502. }
  24503. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  24504. };
  24505. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  24506. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  24507. };
  24508. Scene.prototype._renderForCamera = function (camera, rigParent) {
  24509. if (camera && camera._skipRendering) {
  24510. return;
  24511. }
  24512. var engine = this._engine;
  24513. this.activeCamera = camera;
  24514. if (!this.activeCamera)
  24515. throw new Error("Active camera not set");
  24516. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24517. // Viewport
  24518. engine.setViewport(this.activeCamera.viewport);
  24519. // Camera
  24520. this.resetCachedMaterial();
  24521. this._renderId++;
  24522. this.updateTransformMatrix();
  24523. if (camera._alternateCamera) {
  24524. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24525. this._alternateRendering = true;
  24526. }
  24527. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24528. // Meshes
  24529. this._evaluateActiveMeshes();
  24530. // Software skinning
  24531. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24532. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24533. mesh.applySkeleton(mesh.skeleton);
  24534. }
  24535. // Render targets
  24536. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24537. var needsRestoreFrameBuffer = false;
  24538. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24539. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24540. }
  24541. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24542. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24543. }
  24544. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24545. this._intermediateRendering = true;
  24546. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24547. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24548. var renderTarget = this._renderTargets.data[renderIndex];
  24549. if (renderTarget._shouldRender()) {
  24550. this._renderId++;
  24551. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24552. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24553. }
  24554. }
  24555. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24556. this._intermediateRendering = false;
  24557. this._renderId++;
  24558. needsRestoreFrameBuffer = true; // Restore back buffer
  24559. }
  24560. // Render EffecttLayer Texture
  24561. var stencilState = this._engine.getStencilBuffer();
  24562. var renderEffects = false;
  24563. var needStencil = false;
  24564. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24565. this._intermediateRendering = true;
  24566. for (var i = 0; i < this.effectLayers.length; i++) {
  24567. var effectLayer = this.effectLayers[i];
  24568. if (effectLayer.shouldRender() &&
  24569. (!effectLayer.camera ||
  24570. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24571. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24572. renderEffects = true;
  24573. needStencil = needStencil || effectLayer.needStencil();
  24574. var renderTarget = effectLayer._mainTexture;
  24575. if (renderTarget._shouldRender()) {
  24576. this._renderId++;
  24577. renderTarget.render(false, false);
  24578. needsRestoreFrameBuffer = true;
  24579. }
  24580. }
  24581. }
  24582. this._intermediateRendering = false;
  24583. this._renderId++;
  24584. }
  24585. if (needsRestoreFrameBuffer) {
  24586. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24587. }
  24588. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24589. // Prepare Frame
  24590. this.postProcessManager._prepareFrame();
  24591. // Backgrounds
  24592. var layerIndex;
  24593. var layer;
  24594. if (this.layers.length) {
  24595. engine.setDepthBuffer(false);
  24596. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24597. layer = this.layers[layerIndex];
  24598. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24599. layer.render();
  24600. }
  24601. }
  24602. engine.setDepthBuffer(true);
  24603. }
  24604. // Activate effect Layer stencil
  24605. if (needStencil) {
  24606. this._engine.setStencilBuffer(true);
  24607. }
  24608. // Render
  24609. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24610. this._renderingManager.render(null, null, true, true);
  24611. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24612. // Restore effect Layer stencil
  24613. if (needStencil) {
  24614. this._engine.setStencilBuffer(stencilState);
  24615. }
  24616. // Bounding boxes
  24617. if (this._boundingBoxRenderer) {
  24618. this._boundingBoxRenderer.render();
  24619. }
  24620. // Lens flares
  24621. if (this.lensFlaresEnabled) {
  24622. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24623. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24624. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24625. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24626. lensFlareSystem.render();
  24627. }
  24628. }
  24629. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24630. }
  24631. // Foregrounds
  24632. if (this.layers.length) {
  24633. engine.setDepthBuffer(false);
  24634. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24635. layer = this.layers[layerIndex];
  24636. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24637. layer.render();
  24638. }
  24639. }
  24640. engine.setDepthBuffer(true);
  24641. }
  24642. // Effect Layer
  24643. if (renderEffects) {
  24644. engine.setDepthBuffer(false);
  24645. for (var i = 0; i < this.effectLayers.length; i++) {
  24646. if (this.effectLayers[i].shouldRender()) {
  24647. this.effectLayers[i].render();
  24648. }
  24649. }
  24650. engine.setDepthBuffer(true);
  24651. }
  24652. // Finalize frame
  24653. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24654. // Reset some special arrays
  24655. this._renderTargets.reset();
  24656. this._alternateRendering = false;
  24657. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24658. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24659. };
  24660. Scene.prototype._processSubCameras = function (camera) {
  24661. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24662. this._renderForCamera(camera);
  24663. return;
  24664. }
  24665. // rig cameras
  24666. for (var index = 0; index < camera._rigCameras.length; index++) {
  24667. this._renderForCamera(camera._rigCameras[index], camera);
  24668. }
  24669. this.activeCamera = camera;
  24670. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24671. };
  24672. Scene.prototype._checkIntersections = function () {
  24673. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24674. var sourceMesh = this._meshesForIntersections.data[index];
  24675. if (!sourceMesh.actionManager) {
  24676. continue;
  24677. }
  24678. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24679. var action = sourceMesh.actionManager.actions[actionIndex];
  24680. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24681. var parameters = action.getTriggerParameter();
  24682. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24683. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24684. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24685. if (areIntersecting && currentIntersectionInProgress === -1) {
  24686. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24687. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24688. sourceMesh._intersectionsInProgress.push(otherMesh);
  24689. }
  24690. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24691. sourceMesh._intersectionsInProgress.push(otherMesh);
  24692. }
  24693. }
  24694. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24695. //They intersected, and now they don't.
  24696. //is this trigger an exit trigger? execute an event.
  24697. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24698. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24699. }
  24700. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24701. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24702. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24703. }
  24704. }
  24705. }
  24706. }
  24707. }
  24708. };
  24709. Scene.prototype.render = function () {
  24710. if (this.isDisposed) {
  24711. return;
  24712. }
  24713. this._activeParticles.fetchNewFrame();
  24714. this._totalVertices.fetchNewFrame();
  24715. this._activeIndices.fetchNewFrame();
  24716. this._activeBones.fetchNewFrame();
  24717. this._meshesForIntersections.reset();
  24718. this.resetCachedMaterial();
  24719. this.onBeforeAnimationsObservable.notifyObservers(this);
  24720. // Actions
  24721. if (this.actionManager) {
  24722. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24723. }
  24724. //Simplification Queue
  24725. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24726. this.simplificationQueue.executeNext();
  24727. }
  24728. if (this._engine.isDeterministicLockStep()) {
  24729. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24730. var defaultFPS = (60.0 / 1000.0);
  24731. var defaultFrameTime = 1000 / 60; // frame time in MS
  24732. if (this._physicsEngine) {
  24733. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24734. }
  24735. var stepsTaken = 0;
  24736. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24737. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24738. internalSteps = Math.min(internalSteps, maxSubSteps);
  24739. do {
  24740. this.onBeforeStepObservable.notifyObservers(this);
  24741. // Animations
  24742. this._animationRatio = defaultFrameTime * defaultFPS;
  24743. this._animate();
  24744. this.onAfterAnimationsObservable.notifyObservers(this);
  24745. // Physics
  24746. if (this._physicsEngine) {
  24747. this.onBeforePhysicsObservable.notifyObservers(this);
  24748. this._physicsEngine._step(defaultFrameTime / 1000);
  24749. this.onAfterPhysicsObservable.notifyObservers(this);
  24750. }
  24751. this.onAfterStepObservable.notifyObservers(this);
  24752. this._currentStepId++;
  24753. stepsTaken++;
  24754. deltaTime -= defaultFrameTime;
  24755. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24756. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24757. }
  24758. else {
  24759. // Animations
  24760. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24761. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24762. this._animate();
  24763. this.onAfterAnimationsObservable.notifyObservers(this);
  24764. // Physics
  24765. if (this._physicsEngine) {
  24766. this.onBeforePhysicsObservable.notifyObservers(this);
  24767. this._physicsEngine._step(deltaTime / 1000.0);
  24768. this.onAfterPhysicsObservable.notifyObservers(this);
  24769. }
  24770. }
  24771. // update gamepad manager
  24772. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24773. this._gamepadManager._checkGamepadsStatus();
  24774. }
  24775. // Update Cameras
  24776. if (this.activeCameras.length > 0) {
  24777. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24778. var camera = this.activeCameras[cameraIndex];
  24779. camera.update();
  24780. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24781. // rig cameras
  24782. for (var index = 0; index < camera._rigCameras.length; index++) {
  24783. camera._rigCameras[index].update();
  24784. }
  24785. }
  24786. }
  24787. }
  24788. else if (this.activeCamera) {
  24789. this.activeCamera.update();
  24790. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24791. // rig cameras
  24792. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24793. this.activeCamera._rigCameras[index].update();
  24794. }
  24795. }
  24796. }
  24797. // Before render
  24798. this.onBeforeRenderObservable.notifyObservers(this);
  24799. // Customs render targets
  24800. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24801. var engine = this.getEngine();
  24802. var currentActiveCamera = this.activeCamera;
  24803. if (this.renderTargetsEnabled) {
  24804. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24805. this._intermediateRendering = true;
  24806. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24807. var renderTarget = this.customRenderTargets[customIndex];
  24808. if (renderTarget._shouldRender()) {
  24809. this._renderId++;
  24810. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24811. if (!this.activeCamera)
  24812. throw new Error("Active camera not set");
  24813. // Viewport
  24814. engine.setViewport(this.activeCamera.viewport);
  24815. // Camera
  24816. this.updateTransformMatrix();
  24817. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24818. }
  24819. }
  24820. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24821. this._intermediateRendering = false;
  24822. this._renderId++;
  24823. }
  24824. // Restore back buffer
  24825. if (this.customRenderTargets.length > 0) {
  24826. engine.restoreDefaultFramebuffer();
  24827. }
  24828. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24829. this.activeCamera = currentActiveCamera;
  24830. // Procedural textures
  24831. if (this.proceduralTexturesEnabled) {
  24832. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24833. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24834. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24835. if (proceduralTexture._shouldRender()) {
  24836. proceduralTexture.render();
  24837. }
  24838. }
  24839. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24840. }
  24841. // Clear
  24842. if (this.autoClearDepthAndStencil || this.autoClear) {
  24843. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24844. }
  24845. // Shadows
  24846. if (this.shadowsEnabled) {
  24847. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24848. var light = this.lights[lightIndex];
  24849. var shadowGenerator = light.getShadowGenerator();
  24850. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24851. var shadowMap = (shadowGenerator.getShadowMap());
  24852. if (this.textures.indexOf(shadowMap) !== -1) {
  24853. this._renderTargets.push(shadowMap);
  24854. }
  24855. }
  24856. }
  24857. }
  24858. // Depth renderer
  24859. for (var key in this._depthRenderer) {
  24860. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24861. }
  24862. // Geometry renderer
  24863. if (this._geometryBufferRenderer) {
  24864. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24865. }
  24866. // RenderPipeline
  24867. if (this._postProcessRenderPipelineManager) {
  24868. this._postProcessRenderPipelineManager.update();
  24869. }
  24870. // Multi-cameras?
  24871. if (this.activeCameras.length > 0) {
  24872. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24873. if (cameraIndex > 0) {
  24874. this._engine.clear(null, false, true, true);
  24875. }
  24876. this._processSubCameras(this.activeCameras[cameraIndex]);
  24877. }
  24878. }
  24879. else {
  24880. if (!this.activeCamera) {
  24881. throw new Error("No camera defined");
  24882. }
  24883. this._processSubCameras(this.activeCamera);
  24884. }
  24885. // Intersection checks
  24886. this._checkIntersections();
  24887. // Update the audio listener attached to the camera
  24888. if (BABYLON.AudioEngine) {
  24889. this._updateAudioParameters();
  24890. }
  24891. // After render
  24892. if (this.afterRender) {
  24893. this.afterRender();
  24894. }
  24895. this.onAfterRenderObservable.notifyObservers(this);
  24896. // Cleaning
  24897. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24898. var data = this._toBeDisposed.data[index];
  24899. if (data) {
  24900. data.dispose();
  24901. }
  24902. this._toBeDisposed[index] = null;
  24903. }
  24904. this._toBeDisposed.reset();
  24905. if (this.dumpNextRenderTargets) {
  24906. this.dumpNextRenderTargets = false;
  24907. }
  24908. this._activeBones.addCount(0, true);
  24909. this._activeIndices.addCount(0, true);
  24910. this._activeParticles.addCount(0, true);
  24911. };
  24912. Scene.prototype._updateAudioParameters = function () {
  24913. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24914. return;
  24915. }
  24916. var listeningCamera;
  24917. var audioEngine = BABYLON.Engine.audioEngine;
  24918. if (this.activeCameras.length > 0) {
  24919. listeningCamera = this.activeCameras[0];
  24920. }
  24921. else {
  24922. listeningCamera = this.activeCamera;
  24923. }
  24924. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24925. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24926. // for VR cameras
  24927. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24928. listeningCamera = listeningCamera.rigCameras[0];
  24929. }
  24930. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24931. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24932. cameraDirection.normalize();
  24933. // To avoid some errors on GearVR
  24934. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24935. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24936. }
  24937. var i;
  24938. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24939. var sound = this.mainSoundTrack.soundCollection[i];
  24940. if (sound.useCustomAttenuation) {
  24941. sound.updateDistanceFromListener();
  24942. }
  24943. }
  24944. for (i = 0; i < this.soundTracks.length; i++) {
  24945. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24946. sound = this.soundTracks[i].soundCollection[j];
  24947. if (sound.useCustomAttenuation) {
  24948. sound.updateDistanceFromListener();
  24949. }
  24950. }
  24951. }
  24952. }
  24953. };
  24954. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24955. // Audio
  24956. get: function () {
  24957. return this._audioEnabled;
  24958. },
  24959. set: function (value) {
  24960. this._audioEnabled = value;
  24961. if (BABYLON.AudioEngine) {
  24962. if (this._audioEnabled) {
  24963. this._enableAudio();
  24964. }
  24965. else {
  24966. this._disableAudio();
  24967. }
  24968. }
  24969. },
  24970. enumerable: true,
  24971. configurable: true
  24972. });
  24973. Scene.prototype._disableAudio = function () {
  24974. var i;
  24975. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24976. this.mainSoundTrack.soundCollection[i].pause();
  24977. }
  24978. for (i = 0; i < this.soundTracks.length; i++) {
  24979. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24980. this.soundTracks[i].soundCollection[j].pause();
  24981. }
  24982. }
  24983. };
  24984. Scene.prototype._enableAudio = function () {
  24985. var i;
  24986. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24987. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24988. this.mainSoundTrack.soundCollection[i].play();
  24989. }
  24990. }
  24991. for (i = 0; i < this.soundTracks.length; i++) {
  24992. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24993. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24994. this.soundTracks[i].soundCollection[j].play();
  24995. }
  24996. }
  24997. }
  24998. };
  24999. Object.defineProperty(Scene.prototype, "headphone", {
  25000. get: function () {
  25001. return this._headphone;
  25002. },
  25003. set: function (value) {
  25004. this._headphone = value;
  25005. if (BABYLON.AudioEngine) {
  25006. if (this._headphone) {
  25007. this._switchAudioModeForHeadphones();
  25008. }
  25009. else {
  25010. this._switchAudioModeForNormalSpeakers();
  25011. }
  25012. }
  25013. },
  25014. enumerable: true,
  25015. configurable: true
  25016. });
  25017. Scene.prototype._switchAudioModeForHeadphones = function () {
  25018. this.mainSoundTrack.switchPanningModelToHRTF();
  25019. for (var i = 0; i < this.soundTracks.length; i++) {
  25020. this.soundTracks[i].switchPanningModelToHRTF();
  25021. }
  25022. };
  25023. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  25024. this.mainSoundTrack.switchPanningModelToEqualPower();
  25025. for (var i = 0; i < this.soundTracks.length; i++) {
  25026. this.soundTracks[i].switchPanningModelToEqualPower();
  25027. }
  25028. };
  25029. /**
  25030. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  25031. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  25032. * @returns the created depth renderer
  25033. */
  25034. Scene.prototype.enableDepthRenderer = function (camera) {
  25035. camera = camera || this.activeCamera;
  25036. if (!camera) {
  25037. throw "No camera available to enable depth renderer";
  25038. }
  25039. if (!this._depthRenderer[camera.id]) {
  25040. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  25041. }
  25042. return this._depthRenderer[camera.id];
  25043. };
  25044. /**
  25045. * Disables a depth renderer for a given camera
  25046. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  25047. */
  25048. Scene.prototype.disableDepthRenderer = function (camera) {
  25049. camera = camera || this.activeCamera;
  25050. if (!camera || !this._depthRenderer[camera.id]) {
  25051. return;
  25052. }
  25053. this._depthRenderer[camera.id].dispose();
  25054. delete this._depthRenderer[camera.id];
  25055. };
  25056. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  25057. if (ratio === void 0) { ratio = 1; }
  25058. if (this._geometryBufferRenderer) {
  25059. return this._geometryBufferRenderer;
  25060. }
  25061. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  25062. if (!this._geometryBufferRenderer.isSupported) {
  25063. this._geometryBufferRenderer = null;
  25064. }
  25065. return this._geometryBufferRenderer;
  25066. };
  25067. Scene.prototype.disableGeometryBufferRenderer = function () {
  25068. if (!this._geometryBufferRenderer) {
  25069. return;
  25070. }
  25071. this._geometryBufferRenderer.dispose();
  25072. this._geometryBufferRenderer = null;
  25073. };
  25074. Scene.prototype.freezeMaterials = function () {
  25075. for (var i = 0; i < this.materials.length; i++) {
  25076. this.materials[i].freeze();
  25077. }
  25078. };
  25079. Scene.prototype.unfreezeMaterials = function () {
  25080. for (var i = 0; i < this.materials.length; i++) {
  25081. this.materials[i].unfreeze();
  25082. }
  25083. };
  25084. Scene.prototype.dispose = function () {
  25085. this.beforeRender = null;
  25086. this.afterRender = null;
  25087. this.skeletons = [];
  25088. this.morphTargetManagers = [];
  25089. this.importedMeshesFiles = new Array();
  25090. this.stopAllAnimations();
  25091. this.resetCachedMaterial();
  25092. for (var key in this._depthRenderer) {
  25093. this._depthRenderer[key].dispose();
  25094. }
  25095. if (this._gamepadManager) {
  25096. this._gamepadManager.dispose();
  25097. this._gamepadManager = null;
  25098. }
  25099. // Smart arrays
  25100. if (this.activeCamera) {
  25101. this.activeCamera._activeMeshes.dispose();
  25102. this.activeCamera = null;
  25103. }
  25104. this._activeMeshes.dispose();
  25105. this._renderingManager.dispose();
  25106. this._processedMaterials.dispose();
  25107. this._activeParticleSystems.dispose();
  25108. this._activeSkeletons.dispose();
  25109. this._softwareSkinnedMeshes.dispose();
  25110. this._renderTargets.dispose();
  25111. this._registeredForLateAnimationBindings.dispose();
  25112. if (this._boundingBoxRenderer) {
  25113. this._boundingBoxRenderer.dispose();
  25114. }
  25115. this._meshesForIntersections.dispose();
  25116. this._toBeDisposed.dispose();
  25117. // Abort active requests
  25118. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  25119. var request = _a[_i];
  25120. request.abort();
  25121. }
  25122. // Debug layer
  25123. if (this._debugLayer) {
  25124. this._debugLayer.hide();
  25125. }
  25126. // Events
  25127. this.onDisposeObservable.notifyObservers(this);
  25128. this.onDisposeObservable.clear();
  25129. this.onBeforeRenderObservable.clear();
  25130. this.onAfterRenderObservable.clear();
  25131. this.OnBeforeRenderTargetsRenderObservable.clear();
  25132. this.OnAfterRenderTargetsRenderObservable.clear();
  25133. this.onAfterStepObservable.clear();
  25134. this.onBeforeStepObservable.clear();
  25135. this.onBeforeActiveMeshesEvaluationObservable.clear();
  25136. this.onAfterActiveMeshesEvaluationObservable.clear();
  25137. this.onBeforeParticlesRenderingObservable.clear();
  25138. this.onAfterParticlesRenderingObservable.clear();
  25139. this.onBeforeSpritesRenderingObservable.clear();
  25140. this.onAfterSpritesRenderingObservable.clear();
  25141. this.onBeforeDrawPhaseObservable.clear();
  25142. this.onAfterDrawPhaseObservable.clear();
  25143. this.onBeforePhysicsObservable.clear();
  25144. this.onAfterPhysicsObservable.clear();
  25145. this.onBeforeAnimationsObservable.clear();
  25146. this.onAfterAnimationsObservable.clear();
  25147. this.onDataLoadedObservable.clear();
  25148. this.detachControl();
  25149. // Release sounds & sounds tracks
  25150. if (BABYLON.AudioEngine) {
  25151. this.disposeSounds();
  25152. }
  25153. // VR Helper
  25154. if (this.VRHelper) {
  25155. this.VRHelper.dispose();
  25156. }
  25157. // Detach cameras
  25158. var canvas = this._engine.getRenderingCanvas();
  25159. if (canvas) {
  25160. var index;
  25161. for (index = 0; index < this.cameras.length; index++) {
  25162. this.cameras[index].detachControl(canvas);
  25163. }
  25164. }
  25165. // Release animation groups
  25166. while (this.animationGroups.length) {
  25167. this.animationGroups[0].dispose();
  25168. }
  25169. // Release lights
  25170. while (this.lights.length) {
  25171. this.lights[0].dispose();
  25172. }
  25173. // Release meshes
  25174. while (this.meshes.length) {
  25175. this.meshes[0].dispose(true);
  25176. }
  25177. while (this.transformNodes.length) {
  25178. this.removeTransformNode(this.transformNodes[0]);
  25179. }
  25180. // Release cameras
  25181. while (this.cameras.length) {
  25182. this.cameras[0].dispose();
  25183. }
  25184. // Release materials
  25185. if (this.defaultMaterial) {
  25186. this.defaultMaterial.dispose();
  25187. }
  25188. while (this.multiMaterials.length) {
  25189. this.multiMaterials[0].dispose();
  25190. }
  25191. while (this.materials.length) {
  25192. this.materials[0].dispose();
  25193. }
  25194. // Release particles
  25195. while (this.particleSystems.length) {
  25196. this.particleSystems[0].dispose();
  25197. }
  25198. // Release sprites
  25199. while (this.spriteManagers.length) {
  25200. this.spriteManagers[0].dispose();
  25201. }
  25202. // Release postProcesses
  25203. while (this.postProcesses.length) {
  25204. this.postProcesses[0].dispose();
  25205. }
  25206. // Release layers
  25207. while (this.layers.length) {
  25208. this.layers[0].dispose();
  25209. }
  25210. while (this.effectLayers.length) {
  25211. this.effectLayers[0].dispose();
  25212. }
  25213. // Release textures
  25214. while (this.textures.length) {
  25215. this.textures[0].dispose();
  25216. }
  25217. // Release UBO
  25218. this._sceneUbo.dispose();
  25219. if (this._alternateSceneUbo) {
  25220. this._alternateSceneUbo.dispose();
  25221. }
  25222. // Post-processes
  25223. this.postProcessManager.dispose();
  25224. if (this._postProcessRenderPipelineManager) {
  25225. this._postProcessRenderPipelineManager.dispose();
  25226. }
  25227. // Physics
  25228. if (this._physicsEngine) {
  25229. this.disablePhysicsEngine();
  25230. }
  25231. // Remove from engine
  25232. index = this._engine.scenes.indexOf(this);
  25233. if (index > -1) {
  25234. this._engine.scenes.splice(index, 1);
  25235. }
  25236. this._engine.wipeCaches(true);
  25237. this._isDisposed = true;
  25238. };
  25239. Object.defineProperty(Scene.prototype, "isDisposed", {
  25240. get: function () {
  25241. return this._isDisposed;
  25242. },
  25243. enumerable: true,
  25244. configurable: true
  25245. });
  25246. // Release sounds & sounds tracks
  25247. Scene.prototype.disposeSounds = function () {
  25248. if (!this._mainSoundTrack) {
  25249. return;
  25250. }
  25251. this.mainSoundTrack.dispose();
  25252. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  25253. this.soundTracks[scIndex].dispose();
  25254. }
  25255. };
  25256. // Octrees
  25257. /**
  25258. * Get the world extend vectors with an optional filter
  25259. *
  25260. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  25261. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  25262. */
  25263. Scene.prototype.getWorldExtends = function (filterPredicate) {
  25264. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  25265. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  25266. filterPredicate = filterPredicate || (function () { return true; });
  25267. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  25268. mesh.computeWorldMatrix(true);
  25269. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  25270. return;
  25271. }
  25272. var boundingInfo = mesh.getBoundingInfo();
  25273. var minBox = boundingInfo.boundingBox.minimumWorld;
  25274. var maxBox = boundingInfo.boundingBox.maximumWorld;
  25275. BABYLON.Tools.CheckExtends(minBox, min, max);
  25276. BABYLON.Tools.CheckExtends(maxBox, min, max);
  25277. });
  25278. return {
  25279. min: min,
  25280. max: max
  25281. };
  25282. };
  25283. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  25284. if (maxCapacity === void 0) { maxCapacity = 64; }
  25285. if (maxDepth === void 0) { maxDepth = 2; }
  25286. if (!this._selectionOctree) {
  25287. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  25288. }
  25289. var worldExtends = this.getWorldExtends();
  25290. // Update octree
  25291. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  25292. return this._selectionOctree;
  25293. };
  25294. // Picking
  25295. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  25296. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25297. var result = BABYLON.Ray.Zero();
  25298. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  25299. return result;
  25300. };
  25301. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  25302. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25303. var engine = this._engine;
  25304. if (!camera) {
  25305. if (!this.activeCamera)
  25306. throw new Error("Active camera not set");
  25307. camera = this.activeCamera;
  25308. }
  25309. var cameraViewport = camera.viewport;
  25310. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25311. // Moving coordinates to local viewport world
  25312. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25313. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25314. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  25315. return this;
  25316. };
  25317. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  25318. var result = BABYLON.Ray.Zero();
  25319. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  25320. return result;
  25321. };
  25322. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  25323. if (!BABYLON.PickingInfo) {
  25324. return this;
  25325. }
  25326. var engine = this._engine;
  25327. if (!camera) {
  25328. if (!this.activeCamera)
  25329. throw new Error("Active camera not set");
  25330. camera = this.activeCamera;
  25331. }
  25332. var cameraViewport = camera.viewport;
  25333. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25334. var identity = BABYLON.Matrix.Identity();
  25335. // Moving coordinates to local viewport world
  25336. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25337. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25338. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  25339. return this;
  25340. };
  25341. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  25342. if (!BABYLON.PickingInfo) {
  25343. return null;
  25344. }
  25345. var pickingInfo = null;
  25346. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25347. var mesh = this.meshes[meshIndex];
  25348. if (predicate) {
  25349. if (!predicate(mesh)) {
  25350. continue;
  25351. }
  25352. }
  25353. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25354. continue;
  25355. }
  25356. var world = mesh.getWorldMatrix();
  25357. var ray = rayFunction(world);
  25358. var result = mesh.intersects(ray, fastCheck);
  25359. if (!result || !result.hit)
  25360. continue;
  25361. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25362. continue;
  25363. pickingInfo = result;
  25364. if (fastCheck) {
  25365. break;
  25366. }
  25367. }
  25368. return pickingInfo || new BABYLON.PickingInfo();
  25369. };
  25370. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  25371. if (!BABYLON.PickingInfo) {
  25372. return null;
  25373. }
  25374. var pickingInfos = new Array();
  25375. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25376. var mesh = this.meshes[meshIndex];
  25377. if (predicate) {
  25378. if (!predicate(mesh)) {
  25379. continue;
  25380. }
  25381. }
  25382. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25383. continue;
  25384. }
  25385. var world = mesh.getWorldMatrix();
  25386. var ray = rayFunction(world);
  25387. var result = mesh.intersects(ray, false);
  25388. if (!result || !result.hit)
  25389. continue;
  25390. pickingInfos.push(result);
  25391. }
  25392. return pickingInfos;
  25393. };
  25394. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  25395. if (!BABYLON.PickingInfo) {
  25396. return null;
  25397. }
  25398. var pickingInfo = null;
  25399. if (!camera) {
  25400. if (!this.activeCamera) {
  25401. return null;
  25402. }
  25403. camera = this.activeCamera;
  25404. }
  25405. if (this.spriteManagers.length > 0) {
  25406. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  25407. var spriteManager = this.spriteManagers[spriteIndex];
  25408. if (!spriteManager.isPickable) {
  25409. continue;
  25410. }
  25411. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  25412. if (!result || !result.hit)
  25413. continue;
  25414. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25415. continue;
  25416. pickingInfo = result;
  25417. if (fastCheck) {
  25418. break;
  25419. }
  25420. }
  25421. }
  25422. return pickingInfo || new BABYLON.PickingInfo();
  25423. };
  25424. /** Launch a ray to try to pick a mesh in the scene
  25425. * @param x position on screen
  25426. * @param y position on screen
  25427. * @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
  25428. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25429. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25430. */
  25431. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  25432. var _this = this;
  25433. if (!BABYLON.PickingInfo) {
  25434. return null;
  25435. }
  25436. return this._internalPick(function (world) {
  25437. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  25438. return _this._tempPickingRay;
  25439. }, predicate, fastCheck);
  25440. };
  25441. /** Launch a ray to try to pick a sprite in the scene
  25442. * @param x position on screen
  25443. * @param y position on screen
  25444. * @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
  25445. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25446. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25447. */
  25448. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  25449. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  25450. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  25451. };
  25452. /** Use the given ray to pick a mesh in the scene
  25453. * @param ray The ray to use to pick meshes
  25454. * @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
  25455. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25456. */
  25457. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  25458. var _this = this;
  25459. return this._internalPick(function (world) {
  25460. if (!_this._pickWithRayInverseMatrix) {
  25461. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25462. }
  25463. world.invertToRef(_this._pickWithRayInverseMatrix);
  25464. if (!_this._cachedRayForTransform) {
  25465. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25466. }
  25467. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25468. return _this._cachedRayForTransform;
  25469. }, predicate, fastCheck);
  25470. };
  25471. /**
  25472. * Launch a ray to try to pick a mesh in the scene
  25473. * @param x X position on screen
  25474. * @param y Y position on screen
  25475. * @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
  25476. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25477. */
  25478. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  25479. var _this = this;
  25480. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  25481. };
  25482. /**
  25483. * Launch a ray to try to pick a mesh in the scene
  25484. * @param ray Ray to use
  25485. * @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
  25486. */
  25487. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  25488. var _this = this;
  25489. return this._internalMultiPick(function (world) {
  25490. if (!_this._pickWithRayInverseMatrix) {
  25491. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25492. }
  25493. world.invertToRef(_this._pickWithRayInverseMatrix);
  25494. if (!_this._cachedRayForTransform) {
  25495. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25496. }
  25497. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25498. return _this._cachedRayForTransform;
  25499. }, predicate);
  25500. };
  25501. Scene.prototype.setPointerOverMesh = function (mesh) {
  25502. if (this._pointerOverMesh === mesh) {
  25503. return;
  25504. }
  25505. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25506. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25507. }
  25508. this._pointerOverMesh = mesh;
  25509. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25510. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25511. }
  25512. };
  25513. Scene.prototype.getPointerOverMesh = function () {
  25514. return this._pointerOverMesh;
  25515. };
  25516. Scene.prototype.setPointerOverSprite = function (sprite) {
  25517. if (this._pointerOverSprite === sprite) {
  25518. return;
  25519. }
  25520. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25521. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25522. }
  25523. this._pointerOverSprite = sprite;
  25524. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25525. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25526. }
  25527. };
  25528. Scene.prototype.getPointerOverSprite = function () {
  25529. return this._pointerOverSprite;
  25530. };
  25531. // Physics
  25532. Scene.prototype.getPhysicsEngine = function () {
  25533. return this._physicsEngine;
  25534. };
  25535. /**
  25536. * Enables physics to the current scene
  25537. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25538. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25539. * @return {boolean} was the physics engine initialized
  25540. */
  25541. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25542. if (gravity === void 0) { gravity = null; }
  25543. if (this._physicsEngine) {
  25544. return true;
  25545. }
  25546. try {
  25547. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25548. return true;
  25549. }
  25550. catch (e) {
  25551. BABYLON.Tools.Error(e.message);
  25552. return false;
  25553. }
  25554. };
  25555. Scene.prototype.disablePhysicsEngine = function () {
  25556. if (!this._physicsEngine) {
  25557. return;
  25558. }
  25559. this._physicsEngine.dispose();
  25560. this._physicsEngine = null;
  25561. };
  25562. Scene.prototype.isPhysicsEnabled = function () {
  25563. return this._physicsEngine !== undefined;
  25564. };
  25565. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25566. var mesh = compound.parts[0].mesh;
  25567. if (mesh.physicsImpostor) {
  25568. mesh.physicsImpostor.dispose();
  25569. mesh.physicsImpostor = null;
  25570. }
  25571. };
  25572. // Misc.
  25573. Scene.prototype._rebuildGeometries = function () {
  25574. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25575. var geometry = _a[_i];
  25576. geometry._rebuild();
  25577. }
  25578. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25579. var mesh = _c[_b];
  25580. mesh._rebuild();
  25581. }
  25582. if (this.postProcessManager) {
  25583. this.postProcessManager._rebuild();
  25584. }
  25585. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25586. var layer = _e[_d];
  25587. layer._rebuild();
  25588. }
  25589. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25590. var effectLayer = _g[_f];
  25591. effectLayer._rebuild();
  25592. }
  25593. if (this._boundingBoxRenderer) {
  25594. this._boundingBoxRenderer._rebuild();
  25595. }
  25596. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25597. var system = _j[_h];
  25598. system.rebuild();
  25599. }
  25600. if (this._postProcessRenderPipelineManager) {
  25601. this._postProcessRenderPipelineManager._rebuild();
  25602. }
  25603. };
  25604. Scene.prototype._rebuildTextures = function () {
  25605. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25606. var texture = _a[_i];
  25607. texture._rebuild();
  25608. }
  25609. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25610. };
  25611. /**
  25612. * Creates a default light for the scene.
  25613. * @param replace Whether to replace the existing lights in the scene.
  25614. */
  25615. Scene.prototype.createDefaultLight = function (replace) {
  25616. if (replace === void 0) { replace = false; }
  25617. // Dispose existing light in replace mode.
  25618. if (replace) {
  25619. if (this.lights) {
  25620. for (var i = 0; i < this.lights.length; i++) {
  25621. this.lights[i].dispose();
  25622. }
  25623. }
  25624. }
  25625. // Light
  25626. if (this.lights.length === 0) {
  25627. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25628. }
  25629. };
  25630. /**
  25631. * Creates a default camera for the scene.
  25632. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25633. * @param replace Whether to replace the existing active camera in the scene.
  25634. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25635. */
  25636. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25637. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25638. if (replace === void 0) { replace = false; }
  25639. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25640. // Dispose existing camera in replace mode.
  25641. if (replace) {
  25642. if (this.activeCamera) {
  25643. this.activeCamera.dispose();
  25644. this.activeCamera = null;
  25645. }
  25646. }
  25647. // Camera
  25648. if (!this.activeCamera) {
  25649. var worldExtends = this.getWorldExtends();
  25650. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25651. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25652. var camera;
  25653. var radius = worldSize.length() * 1.5;
  25654. // empty scene scenario!
  25655. if (!isFinite(radius)) {
  25656. radius = 1;
  25657. worldCenter.copyFromFloats(0, 0, 0);
  25658. }
  25659. if (createArcRotateCamera) {
  25660. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25661. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25662. arcRotateCamera.wheelPrecision = 100 / radius;
  25663. camera = arcRotateCamera;
  25664. }
  25665. else {
  25666. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25667. freeCamera.setTarget(worldCenter);
  25668. camera = freeCamera;
  25669. }
  25670. camera.minZ = radius * 0.01;
  25671. camera.maxZ = radius * 1000;
  25672. camera.speed = radius * 0.2;
  25673. this.activeCamera = camera;
  25674. var canvas = this.getEngine().getRenderingCanvas();
  25675. if (attachCameraControls && canvas) {
  25676. camera.attachControl(canvas);
  25677. }
  25678. }
  25679. };
  25680. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25681. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25682. if (replace === void 0) { replace = false; }
  25683. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25684. this.createDefaultLight(replace);
  25685. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25686. };
  25687. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25688. if (pbr === void 0) { pbr = false; }
  25689. if (scale === void 0) { scale = 1000; }
  25690. if (blur === void 0) { blur = 0; }
  25691. if (environmentTexture) {
  25692. this.environmentTexture = environmentTexture;
  25693. }
  25694. if (!this.environmentTexture) {
  25695. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25696. return null;
  25697. }
  25698. // Skybox
  25699. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25700. if (pbr) {
  25701. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25702. hdrSkyboxMaterial.backFaceCulling = false;
  25703. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25704. if (hdrSkyboxMaterial.reflectionTexture) {
  25705. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25706. }
  25707. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25708. hdrSkyboxMaterial.disableLighting = true;
  25709. hdrSkyboxMaterial.twoSidedLighting = true;
  25710. hdrSkybox.infiniteDistance = true;
  25711. hdrSkybox.material = hdrSkyboxMaterial;
  25712. }
  25713. else {
  25714. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25715. skyboxMaterial.backFaceCulling = false;
  25716. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25717. if (skyboxMaterial.reflectionTexture) {
  25718. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25719. }
  25720. skyboxMaterial.disableLighting = true;
  25721. hdrSkybox.infiniteDistance = true;
  25722. hdrSkybox.material = skyboxMaterial;
  25723. }
  25724. return hdrSkybox;
  25725. };
  25726. Scene.prototype.createDefaultEnvironment = function (options) {
  25727. if (BABYLON.EnvironmentHelper) {
  25728. return new BABYLON.EnvironmentHelper(options, this);
  25729. }
  25730. return null;
  25731. };
  25732. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25733. if (webVROptions === void 0) { webVROptions = {}; }
  25734. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25735. };
  25736. // Tags
  25737. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25738. if (tagsQuery === undefined) {
  25739. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25740. return list;
  25741. }
  25742. var listByTags = [];
  25743. forEach = forEach || (function (item) { return; });
  25744. for (var i in list) {
  25745. var item = list[i];
  25746. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25747. listByTags.push(item);
  25748. forEach(item);
  25749. }
  25750. }
  25751. return listByTags;
  25752. };
  25753. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25754. return this._getByTags(this.meshes, tagsQuery, forEach);
  25755. };
  25756. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25757. return this._getByTags(this.cameras, tagsQuery, forEach);
  25758. };
  25759. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25760. return this._getByTags(this.lights, tagsQuery, forEach);
  25761. };
  25762. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25763. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25764. };
  25765. /**
  25766. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25767. * This allowed control for front to back rendering or reversly depending of the special needs.
  25768. *
  25769. * @param renderingGroupId The rendering group id corresponding to its index
  25770. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25771. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25772. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25773. */
  25774. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25775. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25776. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25777. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25778. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25779. };
  25780. /**
  25781. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25782. *
  25783. * @param renderingGroupId The rendering group id corresponding to its index
  25784. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25785. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25786. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25787. */
  25788. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25789. if (depth === void 0) { depth = true; }
  25790. if (stencil === void 0) { stencil = true; }
  25791. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25792. };
  25793. /**
  25794. * Will flag all materials as dirty to trigger new shader compilation
  25795. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25796. */
  25797. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25798. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25799. var material = _a[_i];
  25800. if (predicate && !predicate(material)) {
  25801. continue;
  25802. }
  25803. material.markAsDirty(flag);
  25804. }
  25805. };
  25806. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25807. var _this = this;
  25808. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25809. this._activeRequests.push(request);
  25810. request.onCompleteObservable.add(function (request) {
  25811. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25812. });
  25813. return request;
  25814. };
  25815. /** @ignore */
  25816. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25817. var _this = this;
  25818. return new Promise(function (resolve, reject) {
  25819. _this._loadFile(url, function (data) {
  25820. resolve(data);
  25821. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25822. reject(exception);
  25823. });
  25824. });
  25825. };
  25826. // Statics
  25827. Scene._FOGMODE_NONE = 0;
  25828. Scene._FOGMODE_EXP = 1;
  25829. Scene._FOGMODE_EXP2 = 2;
  25830. Scene._FOGMODE_LINEAR = 3;
  25831. Scene._uniqueIdCounter = 0;
  25832. Scene.MinDeltaTime = 1.0;
  25833. Scene.MaxDeltaTime = 1000.0;
  25834. /** The distance in pixel that you have to move to prevent some events */
  25835. Scene.DragMovementThreshold = 10; // in pixels
  25836. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25837. Scene.LongPressDelay = 500; // in milliseconds
  25838. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25839. Scene.DoubleClickDelay = 300; // in milliseconds
  25840. /** If you need to check double click without raising a single click at first click, enable this flag */
  25841. Scene.ExclusiveDoubleClickMode = false;
  25842. return Scene;
  25843. }());
  25844. BABYLON.Scene = Scene;
  25845. })(BABYLON || (BABYLON = {}));
  25846. //# sourceMappingURL=babylon.scene.js.map
  25847. "use strict";
  25848. var BABYLON;
  25849. (function (BABYLON) {
  25850. /**
  25851. * Set of assets to keep when moving a scene into an asset container.
  25852. */
  25853. var KeepAssets = /** @class */ (function () {
  25854. function KeepAssets() {
  25855. /**
  25856. * Cameras to keep.
  25857. */
  25858. this.cameras = new Array();
  25859. /**
  25860. * Lights to keep.
  25861. */
  25862. this.lights = new Array();
  25863. /**
  25864. * Meshes to keep.
  25865. */
  25866. this.meshes = new Array();
  25867. /**
  25868. * Skeletons to keep.
  25869. */
  25870. this.skeletons = new Array();
  25871. /**
  25872. * ParticleSystems to keep.
  25873. */
  25874. this.particleSystems = new Array();
  25875. /**
  25876. * Animations to keep.
  25877. */
  25878. this.animations = new Array();
  25879. /**
  25880. * MultiMaterials to keep.
  25881. */
  25882. this.multiMaterials = new Array();
  25883. /**
  25884. * Materials to keep.
  25885. */
  25886. this.materials = new Array();
  25887. /**
  25888. * MorphTargetManagers to keep.
  25889. */
  25890. this.morphTargetManagers = new Array();
  25891. /**
  25892. * Geometries to keep.
  25893. */
  25894. this.geometries = new Array();
  25895. /**
  25896. * TransformNodes to keep.
  25897. */
  25898. this.transformNodes = new Array();
  25899. /**
  25900. * LensFlareSystems to keep.
  25901. */
  25902. this.lensFlareSystems = new Array();
  25903. /**
  25904. * ShadowGenerators to keep.
  25905. */
  25906. this.shadowGenerators = new Array();
  25907. /**
  25908. * ActionManagers to keep.
  25909. */
  25910. this.actionManagers = new Array();
  25911. /**
  25912. * Sounds to keep.
  25913. */
  25914. this.sounds = new Array();
  25915. }
  25916. return KeepAssets;
  25917. }());
  25918. BABYLON.KeepAssets = KeepAssets;
  25919. /**
  25920. * Container with a set of assets that can be added or removed from a scene.
  25921. */
  25922. var AssetContainer = /** @class */ (function () {
  25923. /**
  25924. * Instantiates an AssetContainer.
  25925. * @param scene The scene the AssetContainer belongs to.
  25926. */
  25927. function AssetContainer(scene) {
  25928. // Objects
  25929. /**
  25930. * Cameras populated in the container.
  25931. */
  25932. this.cameras = new Array();
  25933. /**
  25934. * Lights populated in the container.
  25935. */
  25936. this.lights = new Array();
  25937. /**
  25938. * Meshes populated in the container.
  25939. */
  25940. this.meshes = new Array();
  25941. /**
  25942. * Skeletons populated in the container.
  25943. */
  25944. this.skeletons = new Array();
  25945. /**
  25946. * ParticleSystems populated in the container.
  25947. */
  25948. this.particleSystems = new Array();
  25949. /**
  25950. * Animations populated in the container.
  25951. */
  25952. this.animations = new Array();
  25953. /**
  25954. * MultiMaterials populated in the container.
  25955. */
  25956. this.multiMaterials = new Array();
  25957. /**
  25958. * Materials populated in the container.
  25959. */
  25960. this.materials = new Array();
  25961. /**
  25962. * MorphTargetManagers populated in the container.
  25963. */
  25964. this.morphTargetManagers = new Array();
  25965. /**
  25966. * Geometries populated in the container.
  25967. */
  25968. this.geometries = new Array();
  25969. /**
  25970. * TransformNodes populated in the container.
  25971. */
  25972. this.transformNodes = new Array();
  25973. /**
  25974. * LensFlareSystems populated in the container.
  25975. */
  25976. this.lensFlareSystems = new Array();
  25977. /**
  25978. * ShadowGenerators populated in the container.
  25979. */
  25980. this.shadowGenerators = new Array();
  25981. /**
  25982. * ActionManagers populated in the container.
  25983. */
  25984. this.actionManagers = new Array();
  25985. /**
  25986. * Sounds populated in the container.
  25987. */
  25988. this.sounds = new Array();
  25989. this.scene = scene;
  25990. }
  25991. /**
  25992. * Adds all the assets from the container to the scene.
  25993. */
  25994. AssetContainer.prototype.addAllToScene = function () {
  25995. var _this = this;
  25996. this.cameras.forEach(function (o) {
  25997. _this.scene.addCamera(o);
  25998. });
  25999. this.lights.forEach(function (o) {
  26000. _this.scene.addLight(o);
  26001. });
  26002. this.meshes.forEach(function (o) {
  26003. _this.scene.addMesh(o);
  26004. });
  26005. this.skeletons.forEach(function (o) {
  26006. _this.scene.addSkeleton(o);
  26007. });
  26008. this.particleSystems.forEach(function (o) {
  26009. _this.scene.addParticleSystem(o);
  26010. });
  26011. this.animations.forEach(function (o) {
  26012. _this.scene.addAnimation(o);
  26013. });
  26014. this.multiMaterials.forEach(function (o) {
  26015. _this.scene.addMultiMaterial(o);
  26016. });
  26017. this.materials.forEach(function (o) {
  26018. _this.scene.addMaterial(o);
  26019. });
  26020. this.morphTargetManagers.forEach(function (o) {
  26021. _this.scene.addMorphTargetManager(o);
  26022. });
  26023. this.geometries.forEach(function (o) {
  26024. _this.scene.addGeometry(o);
  26025. });
  26026. this.transformNodes.forEach(function (o) {
  26027. _this.scene.addTransformNode(o);
  26028. });
  26029. this.lensFlareSystems.forEach(function (o) {
  26030. _this.scene.addLensFlareSystem(o);
  26031. });
  26032. this.actionManagers.forEach(function (o) {
  26033. _this.scene.addActionManager(o);
  26034. });
  26035. this.sounds.forEach(function (o) {
  26036. o.play();
  26037. o.autoplay = true;
  26038. _this.scene.mainSoundTrack.AddSound(o);
  26039. });
  26040. };
  26041. /**
  26042. * Removes all the assets in the container from the scene
  26043. */
  26044. AssetContainer.prototype.removeAllFromScene = function () {
  26045. var _this = this;
  26046. this.cameras.forEach(function (o) {
  26047. _this.scene.removeCamera(o);
  26048. });
  26049. this.lights.forEach(function (o) {
  26050. _this.scene.removeLight(o);
  26051. });
  26052. this.meshes.forEach(function (o) {
  26053. _this.scene.removeMesh(o);
  26054. });
  26055. this.skeletons.forEach(function (o) {
  26056. _this.scene.removeSkeleton(o);
  26057. });
  26058. this.particleSystems.forEach(function (o) {
  26059. _this.scene.removeParticleSystem(o);
  26060. });
  26061. this.animations.forEach(function (o) {
  26062. _this.scene.removeAnimation(o);
  26063. });
  26064. this.multiMaterials.forEach(function (o) {
  26065. _this.scene.removeMultiMaterial(o);
  26066. });
  26067. this.materials.forEach(function (o) {
  26068. _this.scene.removeMaterial(o);
  26069. });
  26070. this.morphTargetManagers.forEach(function (o) {
  26071. _this.scene.removeMorphTargetManager(o);
  26072. });
  26073. this.geometries.forEach(function (o) {
  26074. _this.scene.removeGeometry(o);
  26075. });
  26076. this.transformNodes.forEach(function (o) {
  26077. _this.scene.removeTransformNode(o);
  26078. });
  26079. this.lensFlareSystems.forEach(function (o) {
  26080. _this.scene.removeLensFlareSystem(o);
  26081. });
  26082. this.actionManagers.forEach(function (o) {
  26083. _this.scene.removeActionManager(o);
  26084. });
  26085. this.sounds.forEach(function (o) {
  26086. o.stop();
  26087. o.autoplay = false;
  26088. _this.scene.mainSoundTrack.RemoveSound(o);
  26089. });
  26090. };
  26091. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  26092. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  26093. var asset = sourceAssets_1[_i];
  26094. var move = true;
  26095. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  26096. var keepAsset = keepAssets_1[_a];
  26097. if (asset === keepAsset) {
  26098. move = false;
  26099. break;
  26100. }
  26101. }
  26102. if (move) {
  26103. targetAssets.push(asset);
  26104. }
  26105. }
  26106. };
  26107. /**
  26108. * Removes all the assets contained in the scene and adds them to the container.
  26109. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  26110. */
  26111. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  26112. if (keepAssets === undefined) {
  26113. keepAssets = new KeepAssets();
  26114. }
  26115. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  26116. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  26117. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  26118. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  26119. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  26120. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  26121. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  26122. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  26123. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  26124. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  26125. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  26126. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  26127. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  26128. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  26129. this.removeAllFromScene();
  26130. };
  26131. return AssetContainer;
  26132. }());
  26133. BABYLON.AssetContainer = AssetContainer;
  26134. })(BABYLON || (BABYLON = {}));
  26135. //# sourceMappingURL=babylon.assetContainer.js.map
  26136. "use strict";
  26137. var BABYLON;
  26138. (function (BABYLON) {
  26139. var Buffer = /** @class */ (function () {
  26140. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  26141. if (instanced === void 0) { instanced = false; }
  26142. if (engine instanceof BABYLON.Mesh) {
  26143. this._engine = engine.getScene().getEngine();
  26144. }
  26145. else {
  26146. this._engine = engine;
  26147. }
  26148. this._updatable = updatable;
  26149. this._instanced = instanced;
  26150. this._data = data;
  26151. this._strideSize = stride;
  26152. if (!postponeInternalCreation) {
  26153. this.create();
  26154. }
  26155. }
  26156. /**
  26157. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  26158. * @param kind defines the vertex buffer kind (position, normal, etc.)
  26159. * @param offset defines offset in the buffer (0 by default)
  26160. * @param size defines the size in floats of attributes (position is 3 for instance)
  26161. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  26162. * @param instanced defines if the vertex buffer contains indexed data
  26163. * @returns the new vertex buffer
  26164. */
  26165. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  26166. // a lot of these parameters are ignored as they are overriden by the buffer
  26167. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  26168. };
  26169. // Properties
  26170. Buffer.prototype.isUpdatable = function () {
  26171. return this._updatable;
  26172. };
  26173. Buffer.prototype.getData = function () {
  26174. return this._data;
  26175. };
  26176. Buffer.prototype.getBuffer = function () {
  26177. return this._buffer;
  26178. };
  26179. Buffer.prototype.getStrideSize = function () {
  26180. return this._strideSize;
  26181. };
  26182. // public getIsInstanced(): boolean {
  26183. // return this._instanced;
  26184. // }
  26185. // public get instanceDivisor(): number {
  26186. // return this._instanceDivisor;
  26187. // }
  26188. // public set instanceDivisor(value: number) {
  26189. // this._instanceDivisor = value;
  26190. // if (value == 0) {
  26191. // this._instanced = false;
  26192. // } else {
  26193. // this._instanced = true;
  26194. // }
  26195. // }
  26196. // Methods
  26197. Buffer.prototype.create = function (data) {
  26198. if (data === void 0) { data = null; }
  26199. if (!data && this._buffer) {
  26200. return; // nothing to do
  26201. }
  26202. data = data || this._data;
  26203. if (!data) {
  26204. return;
  26205. }
  26206. if (!this._buffer) {
  26207. if (this._updatable) {
  26208. this._buffer = this._engine.createDynamicVertexBuffer(data);
  26209. this._data = data;
  26210. }
  26211. else {
  26212. this._buffer = this._engine.createVertexBuffer(data);
  26213. }
  26214. }
  26215. else if (this._updatable) {
  26216. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  26217. this._data = data;
  26218. }
  26219. };
  26220. Buffer.prototype._rebuild = function () {
  26221. this._buffer = null;
  26222. this.create(this._data);
  26223. };
  26224. Buffer.prototype.update = function (data) {
  26225. this.create(data);
  26226. };
  26227. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  26228. if (!this._buffer) {
  26229. return;
  26230. }
  26231. if (this._updatable) {
  26232. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  26233. this._data = null;
  26234. }
  26235. };
  26236. Buffer.prototype.dispose = function () {
  26237. if (!this._buffer) {
  26238. return;
  26239. }
  26240. if (this._engine._releaseBuffer(this._buffer)) {
  26241. this._buffer = null;
  26242. }
  26243. };
  26244. return Buffer;
  26245. }());
  26246. BABYLON.Buffer = Buffer;
  26247. })(BABYLON || (BABYLON = {}));
  26248. //# sourceMappingURL=babylon.buffer.js.map
  26249. "use strict";
  26250. var BABYLON;
  26251. (function (BABYLON) {
  26252. var VertexBuffer = /** @class */ (function () {
  26253. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  26254. if (data instanceof BABYLON.Buffer) {
  26255. if (!stride) {
  26256. stride = data.getStrideSize();
  26257. }
  26258. this._buffer = data;
  26259. this._ownsBuffer = false;
  26260. }
  26261. else {
  26262. if (!stride) {
  26263. stride = VertexBuffer.DeduceStride(kind);
  26264. }
  26265. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  26266. this._ownsBuffer = true;
  26267. }
  26268. this._stride = stride;
  26269. this._instanced = instanced !== undefined ? instanced : false;
  26270. this._instanceDivisor = instanced ? 1 : 0;
  26271. this._offset = offset ? offset : 0;
  26272. this._size = size ? size : stride;
  26273. this._kind = kind;
  26274. }
  26275. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  26276. /**
  26277. * Gets or sets the instance divisor when in instanced mode
  26278. */
  26279. get: function () {
  26280. return this._instanceDivisor;
  26281. },
  26282. set: function (value) {
  26283. this._instanceDivisor = value;
  26284. if (value == 0) {
  26285. this._instanced = false;
  26286. }
  26287. else {
  26288. this._instanced = true;
  26289. }
  26290. },
  26291. enumerable: true,
  26292. configurable: true
  26293. });
  26294. VertexBuffer.prototype._rebuild = function () {
  26295. if (!this._buffer) {
  26296. return;
  26297. }
  26298. this._buffer._rebuild();
  26299. };
  26300. /**
  26301. * Returns the kind of the VertexBuffer (string).
  26302. */
  26303. VertexBuffer.prototype.getKind = function () {
  26304. return this._kind;
  26305. };
  26306. // Properties
  26307. /**
  26308. * Boolean : is the VertexBuffer updatable ?
  26309. */
  26310. VertexBuffer.prototype.isUpdatable = function () {
  26311. return this._buffer.isUpdatable();
  26312. };
  26313. /**
  26314. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  26315. */
  26316. VertexBuffer.prototype.getData = function () {
  26317. return this._buffer.getData();
  26318. };
  26319. /**
  26320. * Returns the WebGLBuffer associated to the VertexBuffer.
  26321. */
  26322. VertexBuffer.prototype.getBuffer = function () {
  26323. return this._buffer.getBuffer();
  26324. };
  26325. /**
  26326. * Returns the stride of the VertexBuffer (integer).
  26327. */
  26328. VertexBuffer.prototype.getStrideSize = function () {
  26329. return this._stride;
  26330. };
  26331. /**
  26332. * Returns the offset (integer).
  26333. */
  26334. VertexBuffer.prototype.getOffset = function () {
  26335. return this._offset;
  26336. };
  26337. /**
  26338. * Returns the VertexBuffer total size (integer).
  26339. */
  26340. VertexBuffer.prototype.getSize = function () {
  26341. return this._size;
  26342. };
  26343. /**
  26344. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  26345. */
  26346. VertexBuffer.prototype.getIsInstanced = function () {
  26347. return this._instanced;
  26348. };
  26349. /**
  26350. * Returns the instancing divisor, zero for non-instanced (integer).
  26351. */
  26352. VertexBuffer.prototype.getInstanceDivisor = function () {
  26353. return this._instanceDivisor;
  26354. };
  26355. // Methods
  26356. /**
  26357. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  26358. * Returns the created WebGLBuffer.
  26359. */
  26360. VertexBuffer.prototype.create = function (data) {
  26361. return this._buffer.create(data);
  26362. };
  26363. /**
  26364. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26365. * This function will create a new buffer if the current one is not updatable
  26366. * Returns the updated WebGLBuffer.
  26367. */
  26368. VertexBuffer.prototype.update = function (data) {
  26369. return this._buffer.update(data);
  26370. };
  26371. /**
  26372. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26373. * Returns the directly updated WebGLBuffer.
  26374. */
  26375. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  26376. return this._buffer.updateDirectly(data, offset);
  26377. };
  26378. /**
  26379. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  26380. */
  26381. VertexBuffer.prototype.dispose = function () {
  26382. if (this._ownsBuffer) {
  26383. this._buffer.dispose();
  26384. }
  26385. };
  26386. Object.defineProperty(VertexBuffer, "PositionKind", {
  26387. get: function () {
  26388. return VertexBuffer._PositionKind;
  26389. },
  26390. enumerable: true,
  26391. configurable: true
  26392. });
  26393. Object.defineProperty(VertexBuffer, "NormalKind", {
  26394. get: function () {
  26395. return VertexBuffer._NormalKind;
  26396. },
  26397. enumerable: true,
  26398. configurable: true
  26399. });
  26400. Object.defineProperty(VertexBuffer, "TangentKind", {
  26401. get: function () {
  26402. return VertexBuffer._TangentKind;
  26403. },
  26404. enumerable: true,
  26405. configurable: true
  26406. });
  26407. Object.defineProperty(VertexBuffer, "UVKind", {
  26408. get: function () {
  26409. return VertexBuffer._UVKind;
  26410. },
  26411. enumerable: true,
  26412. configurable: true
  26413. });
  26414. Object.defineProperty(VertexBuffer, "UV2Kind", {
  26415. get: function () {
  26416. return VertexBuffer._UV2Kind;
  26417. },
  26418. enumerable: true,
  26419. configurable: true
  26420. });
  26421. Object.defineProperty(VertexBuffer, "UV3Kind", {
  26422. get: function () {
  26423. return VertexBuffer._UV3Kind;
  26424. },
  26425. enumerable: true,
  26426. configurable: true
  26427. });
  26428. Object.defineProperty(VertexBuffer, "UV4Kind", {
  26429. get: function () {
  26430. return VertexBuffer._UV4Kind;
  26431. },
  26432. enumerable: true,
  26433. configurable: true
  26434. });
  26435. Object.defineProperty(VertexBuffer, "UV5Kind", {
  26436. get: function () {
  26437. return VertexBuffer._UV5Kind;
  26438. },
  26439. enumerable: true,
  26440. configurable: true
  26441. });
  26442. Object.defineProperty(VertexBuffer, "UV6Kind", {
  26443. get: function () {
  26444. return VertexBuffer._UV6Kind;
  26445. },
  26446. enumerable: true,
  26447. configurable: true
  26448. });
  26449. Object.defineProperty(VertexBuffer, "ColorKind", {
  26450. get: function () {
  26451. return VertexBuffer._ColorKind;
  26452. },
  26453. enumerable: true,
  26454. configurable: true
  26455. });
  26456. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  26457. get: function () {
  26458. return VertexBuffer._MatricesIndicesKind;
  26459. },
  26460. enumerable: true,
  26461. configurable: true
  26462. });
  26463. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  26464. get: function () {
  26465. return VertexBuffer._MatricesWeightsKind;
  26466. },
  26467. enumerable: true,
  26468. configurable: true
  26469. });
  26470. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  26471. get: function () {
  26472. return VertexBuffer._MatricesIndicesExtraKind;
  26473. },
  26474. enumerable: true,
  26475. configurable: true
  26476. });
  26477. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  26478. get: function () {
  26479. return VertexBuffer._MatricesWeightsExtraKind;
  26480. },
  26481. enumerable: true,
  26482. configurable: true
  26483. });
  26484. /**
  26485. * Deduces the stride given a kind.
  26486. * @param kind The kind string to deduce
  26487. * @returns The deduced stride
  26488. */
  26489. VertexBuffer.DeduceStride = function (kind) {
  26490. switch (kind) {
  26491. case VertexBuffer.UVKind:
  26492. case VertexBuffer.UV2Kind:
  26493. case VertexBuffer.UV3Kind:
  26494. case VertexBuffer.UV4Kind:
  26495. case VertexBuffer.UV5Kind:
  26496. case VertexBuffer.UV6Kind:
  26497. return 2;
  26498. case VertexBuffer.NormalKind:
  26499. case VertexBuffer.PositionKind:
  26500. return 3;
  26501. case VertexBuffer.ColorKind:
  26502. case VertexBuffer.MatricesIndicesKind:
  26503. case VertexBuffer.MatricesIndicesExtraKind:
  26504. case VertexBuffer.MatricesWeightsKind:
  26505. case VertexBuffer.MatricesWeightsExtraKind:
  26506. case VertexBuffer.TangentKind:
  26507. return 4;
  26508. default:
  26509. throw new Error("Invalid kind '" + kind + "'");
  26510. }
  26511. };
  26512. // Enums
  26513. VertexBuffer._PositionKind = "position";
  26514. VertexBuffer._NormalKind = "normal";
  26515. VertexBuffer._TangentKind = "tangent";
  26516. VertexBuffer._UVKind = "uv";
  26517. VertexBuffer._UV2Kind = "uv2";
  26518. VertexBuffer._UV3Kind = "uv3";
  26519. VertexBuffer._UV4Kind = "uv4";
  26520. VertexBuffer._UV5Kind = "uv5";
  26521. VertexBuffer._UV6Kind = "uv6";
  26522. VertexBuffer._ColorKind = "color";
  26523. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  26524. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  26525. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  26526. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26527. return VertexBuffer;
  26528. }());
  26529. BABYLON.VertexBuffer = VertexBuffer;
  26530. })(BABYLON || (BABYLON = {}));
  26531. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26532. "use strict";
  26533. var BABYLON;
  26534. (function (BABYLON) {
  26535. /**
  26536. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26537. */
  26538. var DummyInternalTextureTracker = /** @class */ (function () {
  26539. function DummyInternalTextureTracker() {
  26540. /**
  26541. * Gets or set the previous tracker in the list
  26542. */
  26543. this.previous = null;
  26544. /**
  26545. * Gets or set the next tracker in the list
  26546. */
  26547. this.next = null;
  26548. }
  26549. return DummyInternalTextureTracker;
  26550. }());
  26551. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26552. })(BABYLON || (BABYLON = {}));
  26553. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26554. "use strict";
  26555. var BABYLON;
  26556. (function (BABYLON) {
  26557. /**
  26558. * Class used to store data associated with WebGL texture data for the engine
  26559. * This class should not be used directly
  26560. */
  26561. var InternalTexture = /** @class */ (function () {
  26562. /**
  26563. * Creates a new InternalTexture
  26564. * @param engine defines the engine to use
  26565. * @param dataSource defines the type of data that will be used
  26566. */
  26567. function InternalTexture(engine, dataSource) {
  26568. /**
  26569. * Observable called when the texture is loaded
  26570. */
  26571. this.onLoadedObservable = new BABYLON.Observable();
  26572. /**
  26573. * Gets or set the previous tracker in the list
  26574. */
  26575. this.previous = null;
  26576. /**
  26577. * Gets or set the next tracker in the list
  26578. */
  26579. this.next = null;
  26580. // Private
  26581. /** @ignore */
  26582. this._initialSlot = -1;
  26583. /** @ignore */
  26584. this._designatedSlot = -1;
  26585. /** @ignore */
  26586. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26587. /** @ignore */
  26588. this._comparisonFunction = 0;
  26589. /** @ignore */
  26590. this._references = 1;
  26591. this._engine = engine;
  26592. this._dataSource = dataSource;
  26593. this._webGLTexture = engine._createTexture();
  26594. }
  26595. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26596. /**
  26597. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26598. */
  26599. get: function () {
  26600. return this._dataSource;
  26601. },
  26602. enumerable: true,
  26603. configurable: true
  26604. });
  26605. /**
  26606. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26607. */
  26608. InternalTexture.prototype.incrementReferences = function () {
  26609. this._references++;
  26610. };
  26611. /**
  26612. * Change the size of the texture (not the size of the content)
  26613. * @param width defines the new width
  26614. * @param height defines the new height
  26615. * @param depth defines the new depth (1 by default)
  26616. */
  26617. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26618. if (depth === void 0) { depth = 1; }
  26619. this.width = width;
  26620. this.height = height;
  26621. this.depth = depth;
  26622. this.baseWidth = width;
  26623. this.baseHeight = height;
  26624. this.baseDepth = depth;
  26625. this._size = width * height * depth;
  26626. };
  26627. /** @ignore */
  26628. InternalTexture.prototype._rebuild = function () {
  26629. var _this = this;
  26630. var proxy;
  26631. this.isReady = false;
  26632. this._cachedCoordinatesMode = null;
  26633. this._cachedWrapU = null;
  26634. this._cachedWrapV = null;
  26635. this._cachedAnisotropicFilteringLevel = null;
  26636. switch (this._dataSource) {
  26637. case InternalTexture.DATASOURCE_TEMP:
  26638. return;
  26639. case InternalTexture.DATASOURCE_URL:
  26640. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26641. _this.isReady = true;
  26642. }, null, this._buffer, undefined, this.format);
  26643. proxy._swapAndDie(this);
  26644. return;
  26645. case InternalTexture.DATASOURCE_RAW:
  26646. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26647. proxy._swapAndDie(this);
  26648. this.isReady = true;
  26649. return;
  26650. case InternalTexture.DATASOURCE_RAW3D:
  26651. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26652. proxy._swapAndDie(this);
  26653. this.isReady = true;
  26654. return;
  26655. case InternalTexture.DATASOURCE_DYNAMIC:
  26656. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26657. proxy._swapAndDie(this);
  26658. // The engine will make sure to update content so no need to flag it as isReady = true
  26659. return;
  26660. case InternalTexture.DATASOURCE_RENDERTARGET:
  26661. var options = new BABYLON.RenderTargetCreationOptions();
  26662. options.generateDepthBuffer = this._generateDepthBuffer;
  26663. options.generateMipMaps = this.generateMipMaps;
  26664. options.generateStencilBuffer = this._generateStencilBuffer;
  26665. options.samplingMode = this.samplingMode;
  26666. options.type = this.type;
  26667. if (this.isCube) {
  26668. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26669. }
  26670. else {
  26671. var size = {
  26672. width: this.width,
  26673. height: this.height
  26674. };
  26675. proxy = this._engine.createRenderTargetTexture(size, options);
  26676. }
  26677. proxy._swapAndDie(this);
  26678. this.isReady = true;
  26679. return;
  26680. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26681. var depthTextureOptions = {
  26682. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26683. comparisonFunction: this._comparisonFunction,
  26684. generateStencil: this._generateStencilBuffer,
  26685. isCube: this.isCube
  26686. };
  26687. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26688. proxy._swapAndDie(this);
  26689. this.isReady = true;
  26690. return;
  26691. case InternalTexture.DATASOURCE_CUBE:
  26692. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26693. _this.isReady = true;
  26694. }, null, this.format, this._extension);
  26695. proxy._swapAndDie(this);
  26696. return;
  26697. case InternalTexture.DATASOURCE_CUBERAW:
  26698. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26699. proxy._swapAndDie(this);
  26700. this.isReady = true;
  26701. return;
  26702. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26703. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26704. if (proxy) {
  26705. proxy._swapAndDie(_this);
  26706. }
  26707. _this.isReady = true;
  26708. }, null, this.format, this._extension);
  26709. return;
  26710. }
  26711. };
  26712. InternalTexture.prototype._swapAndDie = function (target) {
  26713. target._webGLTexture = this._webGLTexture;
  26714. if (this._framebuffer) {
  26715. target._framebuffer = this._framebuffer;
  26716. }
  26717. if (this._depthStencilBuffer) {
  26718. target._depthStencilBuffer = this._depthStencilBuffer;
  26719. }
  26720. if (this._lodTextureHigh) {
  26721. if (target._lodTextureHigh) {
  26722. target._lodTextureHigh.dispose();
  26723. }
  26724. target._lodTextureHigh = this._lodTextureHigh;
  26725. }
  26726. if (this._lodTextureMid) {
  26727. if (target._lodTextureMid) {
  26728. target._lodTextureMid.dispose();
  26729. }
  26730. target._lodTextureMid = this._lodTextureMid;
  26731. }
  26732. if (this._lodTextureLow) {
  26733. if (target._lodTextureLow) {
  26734. target._lodTextureLow.dispose();
  26735. }
  26736. target._lodTextureLow = this._lodTextureLow;
  26737. }
  26738. var cache = this._engine.getLoadedTexturesCache();
  26739. var index = cache.indexOf(this);
  26740. if (index !== -1) {
  26741. cache.splice(index, 1);
  26742. }
  26743. };
  26744. /**
  26745. * Dispose the current allocated resources
  26746. */
  26747. InternalTexture.prototype.dispose = function () {
  26748. if (!this._webGLTexture) {
  26749. return;
  26750. }
  26751. this._references--;
  26752. if (this._references === 0) {
  26753. this._engine._releaseTexture(this);
  26754. this._webGLTexture = null;
  26755. this.previous = null;
  26756. this.next = null;
  26757. }
  26758. };
  26759. /**
  26760. * The source of the texture data is unknown
  26761. */
  26762. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26763. /**
  26764. * Texture data comes from an URL
  26765. */
  26766. InternalTexture.DATASOURCE_URL = 1;
  26767. /**
  26768. * Texture data is only used for temporary storage
  26769. */
  26770. InternalTexture.DATASOURCE_TEMP = 2;
  26771. /**
  26772. * Texture data comes from raw data (ArrayBuffer)
  26773. */
  26774. InternalTexture.DATASOURCE_RAW = 3;
  26775. /**
  26776. * Texture content is dynamic (video or dynamic texture)
  26777. */
  26778. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26779. /**
  26780. * Texture content is generated by rendering to it
  26781. */
  26782. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26783. /**
  26784. * Texture content is part of a multi render target process
  26785. */
  26786. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26787. /**
  26788. * Texture data comes from a cube data file
  26789. */
  26790. InternalTexture.DATASOURCE_CUBE = 7;
  26791. /**
  26792. * Texture data comes from a raw cube data
  26793. */
  26794. InternalTexture.DATASOURCE_CUBERAW = 8;
  26795. /**
  26796. * Texture data come from a prefiltered cube data file
  26797. */
  26798. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26799. /**
  26800. * Texture content is raw 3D data
  26801. */
  26802. InternalTexture.DATASOURCE_RAW3D = 10;
  26803. /**
  26804. * Texture content is a depth texture
  26805. */
  26806. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26807. return InternalTexture;
  26808. }());
  26809. BABYLON.InternalTexture = InternalTexture;
  26810. })(BABYLON || (BABYLON = {}));
  26811. //# sourceMappingURL=babylon.internalTexture.js.map
  26812. "use strict";
  26813. var BABYLON;
  26814. (function (BABYLON) {
  26815. var BaseTexture = /** @class */ (function () {
  26816. function BaseTexture(scene) {
  26817. this._hasAlpha = false;
  26818. this.getAlphaFromRGB = false;
  26819. this.level = 1;
  26820. this.coordinatesIndex = 0;
  26821. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26822. /**
  26823. * | Value | Type | Description |
  26824. * | ----- | ------------------ | ----------- |
  26825. * | 0 | CLAMP_ADDRESSMODE | |
  26826. * | 1 | WRAP_ADDRESSMODE | |
  26827. * | 2 | MIRROR_ADDRESSMODE | |
  26828. */
  26829. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26830. /**
  26831. * | Value | Type | Description |
  26832. * | ----- | ------------------ | ----------- |
  26833. * | 0 | CLAMP_ADDRESSMODE | |
  26834. * | 1 | WRAP_ADDRESSMODE | |
  26835. * | 2 | MIRROR_ADDRESSMODE | |
  26836. */
  26837. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26838. /**
  26839. * | Value | Type | Description |
  26840. * | ----- | ------------------ | ----------- |
  26841. * | 0 | CLAMP_ADDRESSMODE | |
  26842. * | 1 | WRAP_ADDRESSMODE | |
  26843. * | 2 | MIRROR_ADDRESSMODE | |
  26844. */
  26845. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26846. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26847. this.isCube = false;
  26848. this.is3D = false;
  26849. this.gammaSpace = true;
  26850. this.invertZ = false;
  26851. this.lodLevelInAlpha = false;
  26852. this.lodGenerationOffset = 0.0;
  26853. this.lodGenerationScale = 0.8;
  26854. this.isRenderTarget = false;
  26855. this.animations = new Array();
  26856. /**
  26857. * An event triggered when the texture is disposed.
  26858. * @type {BABYLON.Observable}
  26859. */
  26860. this.onDisposeObservable = new BABYLON.Observable();
  26861. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26862. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26863. if (this._scene) {
  26864. this._scene.textures.push(this);
  26865. }
  26866. this._uid = null;
  26867. }
  26868. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26869. get: function () {
  26870. return this._hasAlpha;
  26871. },
  26872. set: function (value) {
  26873. if (this._hasAlpha === value) {
  26874. return;
  26875. }
  26876. this._hasAlpha = value;
  26877. if (this._scene) {
  26878. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26879. }
  26880. },
  26881. enumerable: true,
  26882. configurable: true
  26883. });
  26884. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26885. get: function () {
  26886. return this._coordinatesMode;
  26887. },
  26888. /**
  26889. * How a texture is mapped.
  26890. *
  26891. * | Value | Type | Description |
  26892. * | ----- | ----------------------------------- | ----------- |
  26893. * | 0 | EXPLICIT_MODE | |
  26894. * | 1 | SPHERICAL_MODE | |
  26895. * | 2 | PLANAR_MODE | |
  26896. * | 3 | CUBIC_MODE | |
  26897. * | 4 | PROJECTION_MODE | |
  26898. * | 5 | SKYBOX_MODE | |
  26899. * | 6 | INVCUBIC_MODE | |
  26900. * | 7 | EQUIRECTANGULAR_MODE | |
  26901. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26902. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26903. */
  26904. set: function (value) {
  26905. if (this._coordinatesMode === value) {
  26906. return;
  26907. }
  26908. this._coordinatesMode = value;
  26909. if (this._scene) {
  26910. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26911. }
  26912. },
  26913. enumerable: true,
  26914. configurable: true
  26915. });
  26916. Object.defineProperty(BaseTexture.prototype, "uid", {
  26917. get: function () {
  26918. if (!this._uid) {
  26919. this._uid = BABYLON.Tools.RandomId();
  26920. }
  26921. return this._uid;
  26922. },
  26923. enumerable: true,
  26924. configurable: true
  26925. });
  26926. BaseTexture.prototype.toString = function () {
  26927. return this.name;
  26928. };
  26929. BaseTexture.prototype.getClassName = function () {
  26930. return "BaseTexture";
  26931. };
  26932. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26933. set: function (callback) {
  26934. if (this._onDisposeObserver) {
  26935. this.onDisposeObservable.remove(this._onDisposeObserver);
  26936. }
  26937. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26938. },
  26939. enumerable: true,
  26940. configurable: true
  26941. });
  26942. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26943. get: function () {
  26944. return true;
  26945. },
  26946. enumerable: true,
  26947. configurable: true
  26948. });
  26949. BaseTexture.prototype.getScene = function () {
  26950. return this._scene;
  26951. };
  26952. BaseTexture.prototype.getTextureMatrix = function () {
  26953. return BABYLON.Matrix.IdentityReadOnly;
  26954. };
  26955. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26956. return BABYLON.Matrix.IdentityReadOnly;
  26957. };
  26958. BaseTexture.prototype.getInternalTexture = function () {
  26959. return this._texture;
  26960. };
  26961. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26962. return !this.isBlocking || this.isReady();
  26963. };
  26964. BaseTexture.prototype.isReady = function () {
  26965. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26966. this.delayLoad();
  26967. return false;
  26968. }
  26969. if (this._texture) {
  26970. return this._texture.isReady;
  26971. }
  26972. return false;
  26973. };
  26974. BaseTexture.prototype.getSize = function () {
  26975. if (this._texture && this._texture.width) {
  26976. return new BABYLON.Size(this._texture.width, this._texture.height);
  26977. }
  26978. if (this._texture && this._texture._size) {
  26979. return new BABYLON.Size(this._texture._size, this._texture._size);
  26980. }
  26981. return BABYLON.Size.Zero();
  26982. };
  26983. BaseTexture.prototype.getBaseSize = function () {
  26984. if (!this.isReady() || !this._texture)
  26985. return BABYLON.Size.Zero();
  26986. if (this._texture._size) {
  26987. return new BABYLON.Size(this._texture._size, this._texture._size);
  26988. }
  26989. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  26990. };
  26991. BaseTexture.prototype.scale = function (ratio) {
  26992. };
  26993. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26994. get: function () {
  26995. return false;
  26996. },
  26997. enumerable: true,
  26998. configurable: true
  26999. });
  27000. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  27001. if (!this._scene) {
  27002. return null;
  27003. }
  27004. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  27005. for (var index = 0; index < texturesCache.length; index++) {
  27006. var texturesCacheEntry = texturesCache[index];
  27007. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  27008. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  27009. texturesCacheEntry.incrementReferences();
  27010. return texturesCacheEntry;
  27011. }
  27012. }
  27013. }
  27014. return null;
  27015. };
  27016. BaseTexture.prototype._rebuild = function () {
  27017. };
  27018. BaseTexture.prototype.delayLoad = function () {
  27019. };
  27020. BaseTexture.prototype.clone = function () {
  27021. return null;
  27022. };
  27023. Object.defineProperty(BaseTexture.prototype, "textureType", {
  27024. get: function () {
  27025. if (!this._texture) {
  27026. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27027. }
  27028. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27029. },
  27030. enumerable: true,
  27031. configurable: true
  27032. });
  27033. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  27034. get: function () {
  27035. if (!this._texture) {
  27036. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27037. }
  27038. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27039. },
  27040. enumerable: true,
  27041. configurable: true
  27042. });
  27043. BaseTexture.prototype.readPixels = function (faceIndex) {
  27044. if (faceIndex === void 0) { faceIndex = 0; }
  27045. if (!this._texture) {
  27046. return null;
  27047. }
  27048. var size = this.getSize();
  27049. var scene = this.getScene();
  27050. if (!scene) {
  27051. return null;
  27052. }
  27053. var engine = scene.getEngine();
  27054. if (this._texture.isCube) {
  27055. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  27056. }
  27057. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  27058. };
  27059. BaseTexture.prototype.releaseInternalTexture = function () {
  27060. if (this._texture) {
  27061. this._texture.dispose();
  27062. this._texture = null;
  27063. }
  27064. };
  27065. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  27066. get: function () {
  27067. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  27068. return null;
  27069. }
  27070. if (!this._texture._sphericalPolynomial) {
  27071. this._texture._sphericalPolynomial =
  27072. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  27073. }
  27074. return this._texture._sphericalPolynomial;
  27075. },
  27076. set: function (value) {
  27077. if (this._texture) {
  27078. this._texture._sphericalPolynomial = value;
  27079. }
  27080. },
  27081. enumerable: true,
  27082. configurable: true
  27083. });
  27084. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  27085. get: function () {
  27086. if (this._texture) {
  27087. return this._texture._lodTextureHigh;
  27088. }
  27089. return null;
  27090. },
  27091. enumerable: true,
  27092. configurable: true
  27093. });
  27094. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  27095. get: function () {
  27096. if (this._texture) {
  27097. return this._texture._lodTextureMid;
  27098. }
  27099. return null;
  27100. },
  27101. enumerable: true,
  27102. configurable: true
  27103. });
  27104. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  27105. get: function () {
  27106. if (this._texture) {
  27107. return this._texture._lodTextureLow;
  27108. }
  27109. return null;
  27110. },
  27111. enumerable: true,
  27112. configurable: true
  27113. });
  27114. BaseTexture.prototype.dispose = function () {
  27115. if (!this._scene) {
  27116. return;
  27117. }
  27118. // Animations
  27119. this._scene.stopAnimation(this);
  27120. // Remove from scene
  27121. this._scene._removePendingData(this);
  27122. var index = this._scene.textures.indexOf(this);
  27123. if (index >= 0) {
  27124. this._scene.textures.splice(index, 1);
  27125. }
  27126. if (this._texture === undefined) {
  27127. return;
  27128. }
  27129. // Release
  27130. this.releaseInternalTexture();
  27131. // Callback
  27132. this.onDisposeObservable.notifyObservers(this);
  27133. this.onDisposeObservable.clear();
  27134. };
  27135. BaseTexture.prototype.serialize = function () {
  27136. if (!this.name) {
  27137. return null;
  27138. }
  27139. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  27140. // Animations
  27141. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27142. return serializationObject;
  27143. };
  27144. BaseTexture.WhenAllReady = function (textures, callback) {
  27145. var numRemaining = textures.length;
  27146. if (numRemaining === 0) {
  27147. callback();
  27148. return;
  27149. }
  27150. var _loop_1 = function () {
  27151. texture = textures[i];
  27152. if (texture.isReady()) {
  27153. if (--numRemaining === 0) {
  27154. callback();
  27155. }
  27156. }
  27157. else {
  27158. onLoadObservable = texture.onLoadObservable;
  27159. var onLoadCallback_1 = function () {
  27160. onLoadObservable.removeCallback(onLoadCallback_1);
  27161. if (--numRemaining === 0) {
  27162. callback();
  27163. }
  27164. };
  27165. onLoadObservable.add(onLoadCallback_1);
  27166. }
  27167. };
  27168. var texture, onLoadObservable;
  27169. for (var i = 0; i < textures.length; i++) {
  27170. _loop_1();
  27171. }
  27172. };
  27173. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  27174. __decorate([
  27175. BABYLON.serialize()
  27176. ], BaseTexture.prototype, "name", void 0);
  27177. __decorate([
  27178. BABYLON.serialize("hasAlpha")
  27179. ], BaseTexture.prototype, "_hasAlpha", void 0);
  27180. __decorate([
  27181. BABYLON.serialize()
  27182. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  27183. __decorate([
  27184. BABYLON.serialize()
  27185. ], BaseTexture.prototype, "level", void 0);
  27186. __decorate([
  27187. BABYLON.serialize()
  27188. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  27189. __decorate([
  27190. BABYLON.serialize("coordinatesMode")
  27191. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  27192. __decorate([
  27193. BABYLON.serialize()
  27194. ], BaseTexture.prototype, "wrapU", void 0);
  27195. __decorate([
  27196. BABYLON.serialize()
  27197. ], BaseTexture.prototype, "wrapV", void 0);
  27198. __decorate([
  27199. BABYLON.serialize()
  27200. ], BaseTexture.prototype, "wrapR", void 0);
  27201. __decorate([
  27202. BABYLON.serialize()
  27203. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  27204. __decorate([
  27205. BABYLON.serialize()
  27206. ], BaseTexture.prototype, "isCube", void 0);
  27207. __decorate([
  27208. BABYLON.serialize()
  27209. ], BaseTexture.prototype, "is3D", void 0);
  27210. __decorate([
  27211. BABYLON.serialize()
  27212. ], BaseTexture.prototype, "gammaSpace", void 0);
  27213. __decorate([
  27214. BABYLON.serialize()
  27215. ], BaseTexture.prototype, "invertZ", void 0);
  27216. __decorate([
  27217. BABYLON.serialize()
  27218. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  27219. __decorate([
  27220. BABYLON.serialize()
  27221. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  27222. __decorate([
  27223. BABYLON.serialize()
  27224. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  27225. __decorate([
  27226. BABYLON.serialize()
  27227. ], BaseTexture.prototype, "isRenderTarget", void 0);
  27228. return BaseTexture;
  27229. }());
  27230. BABYLON.BaseTexture = BaseTexture;
  27231. })(BABYLON || (BABYLON = {}));
  27232. //# sourceMappingURL=babylon.baseTexture.js.map
  27233. "use strict";
  27234. var BABYLON;
  27235. (function (BABYLON) {
  27236. var Texture = /** @class */ (function (_super) {
  27237. __extends(Texture, _super);
  27238. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  27239. if (noMipmap === void 0) { noMipmap = false; }
  27240. if (invertY === void 0) { invertY = true; }
  27241. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27242. if (onLoad === void 0) { onLoad = null; }
  27243. if (onError === void 0) { onError = null; }
  27244. if (buffer === void 0) { buffer = null; }
  27245. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27246. var _this = _super.call(this, scene) || this;
  27247. _this.uOffset = 0;
  27248. _this.vOffset = 0;
  27249. _this.uScale = 1.0;
  27250. _this.vScale = 1.0;
  27251. _this.uAng = 0;
  27252. _this.vAng = 0;
  27253. _this.wAng = 0;
  27254. _this._isBlocking = true;
  27255. _this.name = url || "";
  27256. _this.url = url;
  27257. _this._noMipmap = noMipmap;
  27258. _this._invertY = invertY;
  27259. _this._samplingMode = samplingMode;
  27260. _this._buffer = buffer;
  27261. _this._deleteBuffer = deleteBuffer;
  27262. if (format) {
  27263. _this._format = format;
  27264. }
  27265. scene = _this.getScene();
  27266. if (!scene) {
  27267. return _this;
  27268. }
  27269. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  27270. var load = function () {
  27271. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  27272. _this.onLoadObservable.notifyObservers(_this);
  27273. }
  27274. if (onLoad) {
  27275. onLoad();
  27276. }
  27277. if (!_this.isBlocking && scene) {
  27278. scene.resetCachedMaterial();
  27279. }
  27280. };
  27281. if (!_this.url) {
  27282. _this._delayedOnLoad = load;
  27283. _this._delayedOnError = onError;
  27284. return _this;
  27285. }
  27286. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  27287. if (!_this._texture) {
  27288. if (!scene.useDelayedTextureLoading) {
  27289. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  27290. if (deleteBuffer) {
  27291. delete _this._buffer;
  27292. }
  27293. }
  27294. else {
  27295. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27296. _this._delayedOnLoad = load;
  27297. _this._delayedOnError = onError;
  27298. }
  27299. }
  27300. else {
  27301. if (_this._texture.isReady) {
  27302. BABYLON.Tools.SetImmediate(function () { return load(); });
  27303. }
  27304. else {
  27305. _this._texture.onLoadedObservable.add(load);
  27306. }
  27307. }
  27308. return _this;
  27309. }
  27310. Object.defineProperty(Texture.prototype, "noMipmap", {
  27311. get: function () {
  27312. return this._noMipmap;
  27313. },
  27314. enumerable: true,
  27315. configurable: true
  27316. });
  27317. Object.defineProperty(Texture.prototype, "isBlocking", {
  27318. get: function () {
  27319. return this._isBlocking;
  27320. },
  27321. set: function (value) {
  27322. this._isBlocking = value;
  27323. },
  27324. enumerable: true,
  27325. configurable: true
  27326. });
  27327. Object.defineProperty(Texture.prototype, "samplingMode", {
  27328. get: function () {
  27329. return this._samplingMode;
  27330. },
  27331. enumerable: true,
  27332. configurable: true
  27333. });
  27334. Texture.prototype.updateURL = function (url) {
  27335. this.url = url;
  27336. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27337. this.delayLoad();
  27338. };
  27339. Texture.prototype.delayLoad = function () {
  27340. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27341. return;
  27342. }
  27343. var scene = this.getScene();
  27344. if (!scene) {
  27345. return;
  27346. }
  27347. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27348. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  27349. if (!this._texture) {
  27350. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  27351. if (this._deleteBuffer) {
  27352. delete this._buffer;
  27353. }
  27354. }
  27355. else {
  27356. if (this._delayedOnLoad) {
  27357. if (this._texture.isReady) {
  27358. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  27359. }
  27360. else {
  27361. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  27362. }
  27363. }
  27364. }
  27365. this._delayedOnLoad = null;
  27366. this._delayedOnError = null;
  27367. };
  27368. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27369. if (!this._texture) {
  27370. return;
  27371. }
  27372. var scene = this.getScene();
  27373. if (!scene) {
  27374. return;
  27375. }
  27376. this._samplingMode = samplingMode;
  27377. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27378. };
  27379. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27380. x *= this.uScale;
  27381. y *= this.vScale;
  27382. x -= 0.5 * this.uScale;
  27383. y -= 0.5 * this.vScale;
  27384. z -= 0.5;
  27385. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27386. t.x += 0.5 * this.uScale + this.uOffset;
  27387. t.y += 0.5 * this.vScale + this.vOffset;
  27388. t.z += 0.5;
  27389. };
  27390. Texture.prototype.getTextureMatrix = function () {
  27391. var _this = this;
  27392. if (this.uOffset === this._cachedUOffset &&
  27393. this.vOffset === this._cachedVOffset &&
  27394. this.uScale === this._cachedUScale &&
  27395. this.vScale === this._cachedVScale &&
  27396. this.uAng === this._cachedUAng &&
  27397. this.vAng === this._cachedVAng &&
  27398. this.wAng === this._cachedWAng) {
  27399. return this._cachedTextureMatrix;
  27400. }
  27401. this._cachedUOffset = this.uOffset;
  27402. this._cachedVOffset = this.vOffset;
  27403. this._cachedUScale = this.uScale;
  27404. this._cachedVScale = this.vScale;
  27405. this._cachedUAng = this.uAng;
  27406. this._cachedVAng = this.vAng;
  27407. this._cachedWAng = this.wAng;
  27408. if (!this._cachedTextureMatrix) {
  27409. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27410. this._rowGenerationMatrix = new BABYLON.Matrix();
  27411. this._t0 = BABYLON.Vector3.Zero();
  27412. this._t1 = BABYLON.Vector3.Zero();
  27413. this._t2 = BABYLON.Vector3.Zero();
  27414. }
  27415. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27416. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27417. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27418. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27419. this._t1.subtractInPlace(this._t0);
  27420. this._t2.subtractInPlace(this._t0);
  27421. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27422. this._cachedTextureMatrix.m[0] = this._t1.x;
  27423. this._cachedTextureMatrix.m[1] = this._t1.y;
  27424. this._cachedTextureMatrix.m[2] = this._t1.z;
  27425. this._cachedTextureMatrix.m[4] = this._t2.x;
  27426. this._cachedTextureMatrix.m[5] = this._t2.y;
  27427. this._cachedTextureMatrix.m[6] = this._t2.z;
  27428. this._cachedTextureMatrix.m[8] = this._t0.x;
  27429. this._cachedTextureMatrix.m[9] = this._t0.y;
  27430. this._cachedTextureMatrix.m[10] = this._t0.z;
  27431. var scene = this.getScene();
  27432. if (!scene) {
  27433. return this._cachedTextureMatrix;
  27434. }
  27435. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27436. return mat.hasTexture(_this);
  27437. });
  27438. return this._cachedTextureMatrix;
  27439. };
  27440. Texture.prototype.getReflectionTextureMatrix = function () {
  27441. var _this = this;
  27442. var scene = this.getScene();
  27443. if (!scene) {
  27444. return this._cachedTextureMatrix;
  27445. }
  27446. if (this.uOffset === this._cachedUOffset &&
  27447. this.vOffset === this._cachedVOffset &&
  27448. this.uScale === this._cachedUScale &&
  27449. this.vScale === this._cachedVScale &&
  27450. this.coordinatesMode === this._cachedCoordinatesMode) {
  27451. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  27452. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  27453. return this._cachedTextureMatrix;
  27454. }
  27455. }
  27456. else {
  27457. return this._cachedTextureMatrix;
  27458. }
  27459. }
  27460. if (!this._cachedTextureMatrix) {
  27461. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27462. }
  27463. if (!this._projectionModeMatrix) {
  27464. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27465. }
  27466. this._cachedUOffset = this.uOffset;
  27467. this._cachedVOffset = this.vOffset;
  27468. this._cachedUScale = this.uScale;
  27469. this._cachedVScale = this.vScale;
  27470. this._cachedCoordinatesMode = this.coordinatesMode;
  27471. switch (this.coordinatesMode) {
  27472. case Texture.PLANAR_MODE:
  27473. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27474. this._cachedTextureMatrix[0] = this.uScale;
  27475. this._cachedTextureMatrix[5] = this.vScale;
  27476. this._cachedTextureMatrix[12] = this.uOffset;
  27477. this._cachedTextureMatrix[13] = this.vOffset;
  27478. break;
  27479. case Texture.PROJECTION_MODE:
  27480. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27481. this._projectionModeMatrix.m[0] = 0.5;
  27482. this._projectionModeMatrix.m[5] = -0.5;
  27483. this._projectionModeMatrix.m[10] = 0.0;
  27484. this._projectionModeMatrix.m[12] = 0.5;
  27485. this._projectionModeMatrix.m[13] = 0.5;
  27486. this._projectionModeMatrix.m[14] = 1.0;
  27487. this._projectionModeMatrix.m[15] = 1.0;
  27488. var projectionMatrix = scene.getProjectionMatrix();
  27489. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  27490. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27491. break;
  27492. default:
  27493. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27494. break;
  27495. }
  27496. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27497. return (mat.getActiveTextures().indexOf(_this) !== -1);
  27498. });
  27499. return this._cachedTextureMatrix;
  27500. };
  27501. Texture.prototype.clone = function () {
  27502. var _this = this;
  27503. return BABYLON.SerializationHelper.Clone(function () {
  27504. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27505. }, this);
  27506. };
  27507. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27508. get: function () {
  27509. if (!this._onLoadObservable) {
  27510. this._onLoadObservable = new BABYLON.Observable();
  27511. }
  27512. return this._onLoadObservable;
  27513. },
  27514. enumerable: true,
  27515. configurable: true
  27516. });
  27517. Texture.prototype.serialize = function () {
  27518. var serializationObject = _super.prototype.serialize.call(this);
  27519. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  27520. serializationObject.base64String = this._buffer;
  27521. serializationObject.name = serializationObject.name.replace("data:", "");
  27522. }
  27523. return serializationObject;
  27524. };
  27525. Texture.prototype.getClassName = function () {
  27526. return "Texture";
  27527. };
  27528. Texture.prototype.dispose = function () {
  27529. _super.prototype.dispose.call(this);
  27530. if (this.onLoadObservable) {
  27531. this.onLoadObservable.clear();
  27532. this._onLoadObservable = null;
  27533. }
  27534. this._delayedOnLoad = null;
  27535. this._delayedOnError = null;
  27536. };
  27537. // Statics
  27538. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27539. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27540. if (onLoad === void 0) { onLoad = null; }
  27541. if (onError === void 0) { onError = null; }
  27542. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27543. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27544. };
  27545. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27546. if (parsedTexture.customType) {
  27547. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27548. // Update Sampling Mode
  27549. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27550. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27551. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27552. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27553. }
  27554. }
  27555. return parsedCustomTexture;
  27556. }
  27557. if (parsedTexture.isCube) {
  27558. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27559. }
  27560. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27561. return null;
  27562. }
  27563. var texture = BABYLON.SerializationHelper.Parse(function () {
  27564. var generateMipMaps = true;
  27565. if (parsedTexture.noMipmap) {
  27566. generateMipMaps = false;
  27567. }
  27568. if (parsedTexture.mirrorPlane) {
  27569. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27570. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27571. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27572. return mirrorTexture;
  27573. }
  27574. else if (parsedTexture.isRenderTarget) {
  27575. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27576. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27577. return renderTargetTexture;
  27578. }
  27579. else {
  27580. var texture;
  27581. if (parsedTexture.base64String) {
  27582. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27583. }
  27584. else {
  27585. var url = rootUrl + parsedTexture.name;
  27586. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27587. url = parsedTexture.url;
  27588. }
  27589. texture = new Texture(url, scene, !generateMipMaps);
  27590. }
  27591. return texture;
  27592. }
  27593. }, parsedTexture, scene);
  27594. // Update Sampling Mode
  27595. if (parsedTexture.samplingMode) {
  27596. var sampling = parsedTexture.samplingMode;
  27597. if (texture._samplingMode !== sampling) {
  27598. texture.updateSamplingMode(sampling);
  27599. }
  27600. }
  27601. // Animations
  27602. if (parsedTexture.animations) {
  27603. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27604. var parsedAnimation = parsedTexture.animations[animationIndex];
  27605. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27606. }
  27607. }
  27608. return texture;
  27609. };
  27610. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27611. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27612. if (noMipmap === void 0) { noMipmap = false; }
  27613. if (invertY === void 0) { invertY = true; }
  27614. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27615. if (onLoad === void 0) { onLoad = null; }
  27616. if (onError === void 0) { onError = null; }
  27617. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27618. if (name.substr(0, 5) !== "data:") {
  27619. name = "data:" + name;
  27620. }
  27621. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27622. };
  27623. // Constants
  27624. Texture.NEAREST_SAMPLINGMODE = 1;
  27625. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27626. Texture.BILINEAR_SAMPLINGMODE = 2;
  27627. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27628. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27629. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27630. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27631. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27632. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27633. Texture.NEAREST_LINEAR = 7;
  27634. Texture.NEAREST_NEAREST = 8;
  27635. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27636. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27637. Texture.LINEAR_LINEAR = 11;
  27638. Texture.LINEAR_NEAREST = 12;
  27639. Texture.EXPLICIT_MODE = 0;
  27640. Texture.SPHERICAL_MODE = 1;
  27641. Texture.PLANAR_MODE = 2;
  27642. Texture.CUBIC_MODE = 3;
  27643. Texture.PROJECTION_MODE = 4;
  27644. Texture.SKYBOX_MODE = 5;
  27645. Texture.INVCUBIC_MODE = 6;
  27646. Texture.EQUIRECTANGULAR_MODE = 7;
  27647. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27648. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27649. Texture.CLAMP_ADDRESSMODE = 0;
  27650. Texture.WRAP_ADDRESSMODE = 1;
  27651. Texture.MIRROR_ADDRESSMODE = 2;
  27652. /**
  27653. * Gets or sets a boolean which defines if the texture url must be build from the serialized URL instead of just using the name and loading them side by side with the scene file
  27654. */
  27655. Texture.UseSerializedUrlIfAny = false;
  27656. __decorate([
  27657. BABYLON.serialize()
  27658. ], Texture.prototype, "url", void 0);
  27659. __decorate([
  27660. BABYLON.serialize()
  27661. ], Texture.prototype, "uOffset", void 0);
  27662. __decorate([
  27663. BABYLON.serialize()
  27664. ], Texture.prototype, "vOffset", void 0);
  27665. __decorate([
  27666. BABYLON.serialize()
  27667. ], Texture.prototype, "uScale", void 0);
  27668. __decorate([
  27669. BABYLON.serialize()
  27670. ], Texture.prototype, "vScale", void 0);
  27671. __decorate([
  27672. BABYLON.serialize()
  27673. ], Texture.prototype, "uAng", void 0);
  27674. __decorate([
  27675. BABYLON.serialize()
  27676. ], Texture.prototype, "vAng", void 0);
  27677. __decorate([
  27678. BABYLON.serialize()
  27679. ], Texture.prototype, "wAng", void 0);
  27680. __decorate([
  27681. BABYLON.serialize()
  27682. ], Texture.prototype, "isBlocking", null);
  27683. return Texture;
  27684. }(BABYLON.BaseTexture));
  27685. BABYLON.Texture = Texture;
  27686. })(BABYLON || (BABYLON = {}));
  27687. //# sourceMappingURL=babylon.texture.js.map
  27688. "use strict";
  27689. var BABYLON;
  27690. (function (BABYLON) {
  27691. var _InstancesBatch = /** @class */ (function () {
  27692. function _InstancesBatch() {
  27693. this.mustReturn = false;
  27694. this.visibleInstances = new Array();
  27695. this.renderSelf = new Array();
  27696. }
  27697. return _InstancesBatch;
  27698. }());
  27699. BABYLON._InstancesBatch = _InstancesBatch;
  27700. var Mesh = /** @class */ (function (_super) {
  27701. __extends(Mesh, _super);
  27702. /**
  27703. * @constructor
  27704. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27705. * @param {Scene} scene The scene to add this mesh to.
  27706. * @param {Node} parent The parent of this mesh, if it has one
  27707. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27708. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27709. * When false, achieved by calling a clone(), also passing False.
  27710. * This will make creation of children, recursive.
  27711. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27712. */
  27713. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27714. if (scene === void 0) { scene = null; }
  27715. if (parent === void 0) { parent = null; }
  27716. if (source === void 0) { source = null; }
  27717. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27718. var _this = _super.call(this, name, scene) || this;
  27719. // Events
  27720. /**
  27721. * An event triggered before rendering the mesh
  27722. * @type {BABYLON.Observable}
  27723. */
  27724. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27725. /**
  27726. * An event triggered after rendering the mesh
  27727. * @type {BABYLON.Observable}
  27728. */
  27729. _this.onAfterRenderObservable = new BABYLON.Observable();
  27730. /**
  27731. * An event triggered before drawing the mesh
  27732. * @type {BABYLON.Observable}
  27733. */
  27734. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27735. // Members
  27736. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27737. _this.instances = new Array();
  27738. _this._LODLevels = new Array();
  27739. _this._visibleInstances = {};
  27740. _this._renderIdForInstances = new Array();
  27741. _this._batchCache = new _InstancesBatch();
  27742. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27743. // Use by builder only to know what orientation were the mesh build in.
  27744. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27745. _this.overrideMaterialSideOrientation = null;
  27746. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27747. // Will be used to save a source mesh reference, If any
  27748. _this._source = null;
  27749. scene = _this.getScene();
  27750. if (source) {
  27751. // Source mesh
  27752. _this._source = source;
  27753. // Geometry
  27754. if (source._geometry) {
  27755. source._geometry.applyToMesh(_this);
  27756. }
  27757. // Deep copy
  27758. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  27759. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  27760. // Metadata
  27761. if (source.metadata && source.metadata.clone) {
  27762. _this.metadata = source.metadata.clone();
  27763. }
  27764. else {
  27765. _this.metadata = source.metadata;
  27766. }
  27767. // Tags
  27768. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27769. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27770. }
  27771. // Parent
  27772. _this.parent = source.parent;
  27773. // Pivot
  27774. _this.setPivotMatrix(source.getPivotMatrix());
  27775. _this.id = name + "." + source.id;
  27776. // Material
  27777. _this.material = source.material;
  27778. var index;
  27779. if (!doNotCloneChildren) {
  27780. // Children
  27781. var directDescendants = source.getDescendants(true);
  27782. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27783. var child = directDescendants[index_1];
  27784. if (child.clone) {
  27785. child.clone(name + "." + child.name, _this);
  27786. }
  27787. }
  27788. }
  27789. // Physics clone
  27790. var physicsEngine = _this.getScene().getPhysicsEngine();
  27791. if (clonePhysicsImpostor && physicsEngine) {
  27792. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27793. if (impostor) {
  27794. _this.physicsImpostor = impostor.clone(_this);
  27795. }
  27796. }
  27797. // Particles
  27798. for (index = 0; index < scene.particleSystems.length; index++) {
  27799. var system = scene.particleSystems[index];
  27800. if (system.emitter === source) {
  27801. system.clone(system.name, _this);
  27802. }
  27803. }
  27804. _this.computeWorldMatrix(true);
  27805. }
  27806. // Parent
  27807. if (parent !== null) {
  27808. _this.parent = parent;
  27809. }
  27810. return _this;
  27811. }
  27812. Object.defineProperty(Mesh, "FRONTSIDE", {
  27813. /**
  27814. * Mesh side orientation : usually the external or front surface
  27815. */
  27816. get: function () {
  27817. return Mesh._FRONTSIDE;
  27818. },
  27819. enumerable: true,
  27820. configurable: true
  27821. });
  27822. Object.defineProperty(Mesh, "BACKSIDE", {
  27823. /**
  27824. * Mesh side orientation : usually the internal or back surface
  27825. */
  27826. get: function () {
  27827. return Mesh._BACKSIDE;
  27828. },
  27829. enumerable: true,
  27830. configurable: true
  27831. });
  27832. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27833. /**
  27834. * Mesh side orientation : both internal and external or front and back surfaces
  27835. */
  27836. get: function () {
  27837. return Mesh._DOUBLESIDE;
  27838. },
  27839. enumerable: true,
  27840. configurable: true
  27841. });
  27842. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27843. /**
  27844. * Mesh side orientation : by default, `FRONTSIDE`
  27845. */
  27846. get: function () {
  27847. return Mesh._DEFAULTSIDE;
  27848. },
  27849. enumerable: true,
  27850. configurable: true
  27851. });
  27852. Object.defineProperty(Mesh, "NO_CAP", {
  27853. /**
  27854. * Mesh cap setting : no cap
  27855. */
  27856. get: function () {
  27857. return Mesh._NO_CAP;
  27858. },
  27859. enumerable: true,
  27860. configurable: true
  27861. });
  27862. Object.defineProperty(Mesh, "CAP_START", {
  27863. /**
  27864. * Mesh cap setting : one cap at the beginning of the mesh
  27865. */
  27866. get: function () {
  27867. return Mesh._CAP_START;
  27868. },
  27869. enumerable: true,
  27870. configurable: true
  27871. });
  27872. Object.defineProperty(Mesh, "CAP_END", {
  27873. /**
  27874. * Mesh cap setting : one cap at the end of the mesh
  27875. */
  27876. get: function () {
  27877. return Mesh._CAP_END;
  27878. },
  27879. enumerable: true,
  27880. configurable: true
  27881. });
  27882. Object.defineProperty(Mesh, "CAP_ALL", {
  27883. /**
  27884. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27885. */
  27886. get: function () {
  27887. return Mesh._CAP_ALL;
  27888. },
  27889. enumerable: true,
  27890. configurable: true
  27891. });
  27892. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27893. set: function (callback) {
  27894. if (this._onBeforeDrawObserver) {
  27895. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27896. }
  27897. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27898. },
  27899. enumerable: true,
  27900. configurable: true
  27901. });
  27902. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27903. get: function () {
  27904. return this._morphTargetManager;
  27905. },
  27906. set: function (value) {
  27907. if (this._morphTargetManager === value) {
  27908. return;
  27909. }
  27910. this._morphTargetManager = value;
  27911. this._syncGeometryWithMorphTargetManager();
  27912. },
  27913. enumerable: true,
  27914. configurable: true
  27915. });
  27916. Object.defineProperty(Mesh.prototype, "source", {
  27917. get: function () {
  27918. return this._source;
  27919. },
  27920. enumerable: true,
  27921. configurable: true
  27922. });
  27923. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27924. get: function () {
  27925. return this._unIndexed;
  27926. },
  27927. set: function (value) {
  27928. if (this._unIndexed !== value) {
  27929. this._unIndexed = value;
  27930. this._markSubMeshesAsAttributesDirty();
  27931. }
  27932. },
  27933. enumerable: true,
  27934. configurable: true
  27935. });
  27936. // Methods
  27937. /**
  27938. * Returns the string "Mesh".
  27939. */
  27940. Mesh.prototype.getClassName = function () {
  27941. return "Mesh";
  27942. };
  27943. /**
  27944. * Returns a string.
  27945. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27946. */
  27947. Mesh.prototype.toString = function (fullDetails) {
  27948. var ret = _super.prototype.toString.call(this, fullDetails);
  27949. ret += ", n vertices: " + this.getTotalVertices();
  27950. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27951. if (this.animations) {
  27952. for (var i = 0; i < this.animations.length; i++) {
  27953. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27954. }
  27955. }
  27956. if (fullDetails) {
  27957. if (this._geometry) {
  27958. var ib = this.getIndices();
  27959. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27960. if (vb && ib) {
  27961. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27962. }
  27963. }
  27964. else {
  27965. ret += ", flat shading: UNKNOWN";
  27966. }
  27967. }
  27968. return ret;
  27969. };
  27970. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27971. /**
  27972. * True if the mesh has some Levels Of Details (LOD).
  27973. * Returns a boolean.
  27974. */
  27975. get: function () {
  27976. return this._LODLevels.length > 0;
  27977. },
  27978. enumerable: true,
  27979. configurable: true
  27980. });
  27981. /**
  27982. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  27983. * @returns an array of {BABYLON.MeshLODLevel}
  27984. */
  27985. Mesh.prototype.getLODLevels = function () {
  27986. return this._LODLevels;
  27987. };
  27988. Mesh.prototype._sortLODLevels = function () {
  27989. this._LODLevels.sort(function (a, b) {
  27990. if (a.distance < b.distance) {
  27991. return 1;
  27992. }
  27993. if (a.distance > b.distance) {
  27994. return -1;
  27995. }
  27996. return 0;
  27997. });
  27998. };
  27999. /**
  28000. * Add a mesh as LOD level triggered at the given distance.
  28001. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28002. * @param {number} distance The distance from the center of the object to show this level
  28003. * @param {Mesh} mesh The mesh to be added as LOD level
  28004. * @return {Mesh} This mesh (for chaining)
  28005. */
  28006. Mesh.prototype.addLODLevel = function (distance, mesh) {
  28007. if (mesh && mesh._masterMesh) {
  28008. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  28009. return this;
  28010. }
  28011. var level = new BABYLON.MeshLODLevel(distance, mesh);
  28012. this._LODLevels.push(level);
  28013. if (mesh) {
  28014. mesh._masterMesh = this;
  28015. }
  28016. this._sortLODLevels();
  28017. return this;
  28018. };
  28019. /**
  28020. * Returns the LOD level mesh at the passed distance or null if not found.
  28021. * It is related to the method `addLODLevel(distance, mesh)`.
  28022. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28023. * Returns an object Mesh or `null`.
  28024. */
  28025. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  28026. for (var index = 0; index < this._LODLevels.length; index++) {
  28027. var level = this._LODLevels[index];
  28028. if (level.distance === distance) {
  28029. return level.mesh;
  28030. }
  28031. }
  28032. return null;
  28033. };
  28034. /**
  28035. * Remove a mesh from the LOD array
  28036. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28037. * @param {Mesh} mesh The mesh to be removed.
  28038. * @return {Mesh} This mesh (for chaining)
  28039. */
  28040. Mesh.prototype.removeLODLevel = function (mesh) {
  28041. for (var index = 0; index < this._LODLevels.length; index++) {
  28042. if (this._LODLevels[index].mesh === mesh) {
  28043. this._LODLevels.splice(index, 1);
  28044. if (mesh) {
  28045. mesh._masterMesh = null;
  28046. }
  28047. }
  28048. }
  28049. this._sortLODLevels();
  28050. return this;
  28051. };
  28052. /**
  28053. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  28054. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28055. */
  28056. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  28057. if (!this._LODLevels || this._LODLevels.length === 0) {
  28058. return this;
  28059. }
  28060. var bSphere;
  28061. if (boundingSphere) {
  28062. bSphere = boundingSphere;
  28063. }
  28064. else {
  28065. var boundingInfo = this.getBoundingInfo();
  28066. bSphere = boundingInfo.boundingSphere;
  28067. }
  28068. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  28069. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  28070. if (this.onLODLevelSelection) {
  28071. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  28072. }
  28073. return this;
  28074. }
  28075. for (var index = 0; index < this._LODLevels.length; index++) {
  28076. var level = this._LODLevels[index];
  28077. if (level.distance < distanceToCamera) {
  28078. if (level.mesh) {
  28079. level.mesh._preActivate();
  28080. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  28081. }
  28082. if (this.onLODLevelSelection) {
  28083. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  28084. }
  28085. return level.mesh;
  28086. }
  28087. }
  28088. if (this.onLODLevelSelection) {
  28089. this.onLODLevelSelection(distanceToCamera, this, this);
  28090. }
  28091. return this;
  28092. };
  28093. Object.defineProperty(Mesh.prototype, "geometry", {
  28094. /**
  28095. * Returns the mesh internal Geometry object.
  28096. */
  28097. get: function () {
  28098. return this._geometry;
  28099. },
  28100. enumerable: true,
  28101. configurable: true
  28102. });
  28103. /**
  28104. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  28105. */
  28106. Mesh.prototype.getTotalVertices = function () {
  28107. if (this._geometry === null || this._geometry === undefined) {
  28108. return 0;
  28109. }
  28110. return this._geometry.getTotalVertices();
  28111. };
  28112. /**
  28113. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  28114. * 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.
  28115. * You can force the copy with forceCopy === true
  28116. * Returns null if the mesh has no geometry or no vertex buffer.
  28117. * Possible `kind` values :
  28118. * - BABYLON.VertexBuffer.PositionKind
  28119. * - BABYLON.VertexBuffer.UVKind
  28120. * - BABYLON.VertexBuffer.UV2Kind
  28121. * - BABYLON.VertexBuffer.UV3Kind
  28122. * - BABYLON.VertexBuffer.UV4Kind
  28123. * - BABYLON.VertexBuffer.UV5Kind
  28124. * - BABYLON.VertexBuffer.UV6Kind
  28125. * - BABYLON.VertexBuffer.ColorKind
  28126. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28127. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28128. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28129. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28130. */
  28131. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  28132. if (!this._geometry) {
  28133. return null;
  28134. }
  28135. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  28136. };
  28137. /**
  28138. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  28139. * Returns `null` if the mesh has no geometry.
  28140. * Possible `kind` values :
  28141. * - BABYLON.VertexBuffer.PositionKind
  28142. * - BABYLON.VertexBuffer.UVKind
  28143. * - BABYLON.VertexBuffer.UV2Kind
  28144. * - BABYLON.VertexBuffer.UV3Kind
  28145. * - BABYLON.VertexBuffer.UV4Kind
  28146. * - BABYLON.VertexBuffer.UV5Kind
  28147. * - BABYLON.VertexBuffer.UV6Kind
  28148. * - BABYLON.VertexBuffer.ColorKind
  28149. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28150. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28151. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28152. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28153. */
  28154. Mesh.prototype.getVertexBuffer = function (kind) {
  28155. if (!this._geometry) {
  28156. return null;
  28157. }
  28158. return this._geometry.getVertexBuffer(kind);
  28159. };
  28160. /**
  28161. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  28162. * Possible `kind` values :
  28163. * - BABYLON.VertexBuffer.PositionKind
  28164. * - BABYLON.VertexBuffer.UVKind
  28165. * - BABYLON.VertexBuffer.UV2Kind
  28166. * - BABYLON.VertexBuffer.UV3Kind
  28167. * - BABYLON.VertexBuffer.UV4Kind
  28168. * - BABYLON.VertexBuffer.UV5Kind
  28169. * - BABYLON.VertexBuffer.UV6Kind
  28170. * - BABYLON.VertexBuffer.ColorKind
  28171. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28172. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28173. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28174. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28175. */
  28176. Mesh.prototype.isVerticesDataPresent = function (kind) {
  28177. if (!this._geometry) {
  28178. if (this._delayInfo) {
  28179. return this._delayInfo.indexOf(kind) !== -1;
  28180. }
  28181. return false;
  28182. }
  28183. return this._geometry.isVerticesDataPresent(kind);
  28184. };
  28185. /**
  28186. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  28187. * Possible `kind` values :
  28188. * - BABYLON.VertexBuffer.PositionKind
  28189. * - BABYLON.VertexBuffer.UVKind
  28190. * - BABYLON.VertexBuffer.UV2Kind
  28191. * - BABYLON.VertexBuffer.UV3Kind
  28192. * - BABYLON.VertexBuffer.UV4Kind
  28193. * - BABYLON.VertexBuffer.UV5Kind
  28194. * - BABYLON.VertexBuffer.UV6Kind
  28195. * - BABYLON.VertexBuffer.ColorKind
  28196. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28197. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28198. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28199. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28200. */
  28201. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  28202. if (!this._geometry) {
  28203. if (this._delayInfo) {
  28204. return this._delayInfo.indexOf(kind) !== -1;
  28205. }
  28206. return false;
  28207. }
  28208. return this._geometry.isVertexBufferUpdatable(kind);
  28209. };
  28210. /**
  28211. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  28212. * Possible `kind` values :
  28213. * - BABYLON.VertexBuffer.PositionKind
  28214. * - BABYLON.VertexBuffer.UVKind
  28215. * - BABYLON.VertexBuffer.UV2Kind
  28216. * - BABYLON.VertexBuffer.UV3Kind
  28217. * - BABYLON.VertexBuffer.UV4Kind
  28218. * - BABYLON.VertexBuffer.UV5Kind
  28219. * - BABYLON.VertexBuffer.UV6Kind
  28220. * - BABYLON.VertexBuffer.ColorKind
  28221. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28222. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28223. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28224. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28225. */
  28226. Mesh.prototype.getVerticesDataKinds = function () {
  28227. if (!this._geometry) {
  28228. var result = new Array();
  28229. if (this._delayInfo) {
  28230. this._delayInfo.forEach(function (kind, index, array) {
  28231. result.push(kind);
  28232. });
  28233. }
  28234. return result;
  28235. }
  28236. return this._geometry.getVerticesDataKinds();
  28237. };
  28238. /**
  28239. * Returns a positive integer : the total number of indices in this mesh geometry.
  28240. * Returns zero if the mesh has no geometry.
  28241. */
  28242. Mesh.prototype.getTotalIndices = function () {
  28243. if (!this._geometry) {
  28244. return 0;
  28245. }
  28246. return this._geometry.getTotalIndices();
  28247. };
  28248. /**
  28249. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  28250. * 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.
  28251. * Returns an empty array if the mesh has no geometry.
  28252. */
  28253. Mesh.prototype.getIndices = function (copyWhenShared) {
  28254. if (!this._geometry) {
  28255. return [];
  28256. }
  28257. return this._geometry.getIndices(copyWhenShared);
  28258. };
  28259. Object.defineProperty(Mesh.prototype, "isBlocked", {
  28260. get: function () {
  28261. return this._masterMesh !== null && this._masterMesh !== undefined;
  28262. },
  28263. enumerable: true,
  28264. configurable: true
  28265. });
  28266. /**
  28267. * Determine if the current mesh is ready to be rendered
  28268. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  28269. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  28270. * @returns true if all associated assets are ready (material, textures, shaders)
  28271. */
  28272. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  28273. if (completeCheck === void 0) { completeCheck = false; }
  28274. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  28275. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28276. return false;
  28277. }
  28278. if (!_super.prototype.isReady.call(this, completeCheck)) {
  28279. return false;
  28280. }
  28281. if (!this.subMeshes || this.subMeshes.length === 0) {
  28282. return true;
  28283. }
  28284. if (!completeCheck) {
  28285. return true;
  28286. }
  28287. var engine = this.getEngine();
  28288. var scene = this.getScene();
  28289. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  28290. this.computeWorldMatrix();
  28291. var mat = this.material || scene.defaultMaterial;
  28292. if (mat) {
  28293. if (mat.storeEffectOnSubMeshes) {
  28294. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28295. var subMesh = _a[_i];
  28296. var effectiveMaterial = subMesh.getMaterial();
  28297. if (effectiveMaterial) {
  28298. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28299. return false;
  28300. }
  28301. }
  28302. }
  28303. }
  28304. else {
  28305. if (!mat.isReady(this, hardwareInstancedRendering)) {
  28306. return false;
  28307. }
  28308. }
  28309. }
  28310. // Shadows
  28311. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  28312. var light = _c[_b];
  28313. var generator = light.getShadowGenerator();
  28314. if (generator) {
  28315. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  28316. var subMesh = _e[_d];
  28317. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  28318. return false;
  28319. }
  28320. }
  28321. }
  28322. }
  28323. // LOD
  28324. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  28325. var lod = _g[_f];
  28326. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  28327. return false;
  28328. }
  28329. }
  28330. return true;
  28331. };
  28332. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  28333. /**
  28334. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  28335. * This property is pertinent only for updatable parametric shapes.
  28336. */
  28337. get: function () {
  28338. return this._areNormalsFrozen;
  28339. },
  28340. enumerable: true,
  28341. configurable: true
  28342. });
  28343. /**
  28344. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28345. * It has no effect at all on other shapes.
  28346. * It prevents the mesh normals from being recomputed on next `positions` array update.
  28347. * Returns the Mesh.
  28348. */
  28349. Mesh.prototype.freezeNormals = function () {
  28350. this._areNormalsFrozen = true;
  28351. return this;
  28352. };
  28353. /**
  28354. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28355. * It has no effect at all on other shapes.
  28356. * It reactivates the mesh normals computation if it was previously frozen.
  28357. * Returns the Mesh.
  28358. */
  28359. Mesh.prototype.unfreezeNormals = function () {
  28360. this._areNormalsFrozen = false;
  28361. return this;
  28362. };
  28363. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  28364. /**
  28365. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  28366. */
  28367. set: function (count) {
  28368. this._overridenInstanceCount = count;
  28369. },
  28370. enumerable: true,
  28371. configurable: true
  28372. });
  28373. // Methods
  28374. Mesh.prototype._preActivate = function () {
  28375. var sceneRenderId = this.getScene().getRenderId();
  28376. if (this._preActivateId === sceneRenderId) {
  28377. return this;
  28378. }
  28379. this._preActivateId = sceneRenderId;
  28380. this._visibleInstances = null;
  28381. return this;
  28382. };
  28383. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  28384. if (this._visibleInstances) {
  28385. this._visibleInstances.intermediateDefaultRenderId = renderId;
  28386. }
  28387. return this;
  28388. };
  28389. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  28390. if (!this._visibleInstances) {
  28391. this._visibleInstances = {};
  28392. this._visibleInstances.defaultRenderId = renderId;
  28393. this._visibleInstances.selfDefaultRenderId = this._renderId;
  28394. }
  28395. if (!this._visibleInstances[renderId]) {
  28396. this._visibleInstances[renderId] = new Array();
  28397. }
  28398. this._visibleInstances[renderId].push(instance);
  28399. return this;
  28400. };
  28401. /**
  28402. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  28403. * This means the mesh underlying bounding box and sphere are recomputed.
  28404. * Returns the Mesh.
  28405. */
  28406. Mesh.prototype.refreshBoundingInfo = function () {
  28407. return this._refreshBoundingInfo(false);
  28408. };
  28409. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  28410. if (this._boundingInfo && this._boundingInfo.isLocked) {
  28411. return this;
  28412. }
  28413. var data = this._getPositionData(applySkeleton);
  28414. if (data) {
  28415. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  28416. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28417. }
  28418. if (this.subMeshes) {
  28419. for (var index = 0; index < this.subMeshes.length; index++) {
  28420. this.subMeshes[index].refreshBoundingInfo();
  28421. }
  28422. }
  28423. this._updateBoundingInfo();
  28424. return this;
  28425. };
  28426. Mesh.prototype._getPositionData = function (applySkeleton) {
  28427. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28428. if (data && applySkeleton && this.skeleton) {
  28429. data = BABYLON.Tools.Slice(data);
  28430. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28431. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28432. if (matricesWeightsData && matricesIndicesData) {
  28433. var needExtras = this.numBoneInfluencers > 4;
  28434. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28435. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28436. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  28437. var tempVector = BABYLON.Tmp.Vector3[0];
  28438. var finalMatrix = BABYLON.Tmp.Matrix[0];
  28439. var tempMatrix = BABYLON.Tmp.Matrix[1];
  28440. var matWeightIdx = 0;
  28441. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  28442. finalMatrix.reset();
  28443. var inf;
  28444. var weight;
  28445. for (inf = 0; inf < 4; inf++) {
  28446. weight = matricesWeightsData[matWeightIdx + inf];
  28447. if (weight <= 0)
  28448. break;
  28449. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28450. finalMatrix.addToSelf(tempMatrix);
  28451. }
  28452. if (needExtras) {
  28453. for (inf = 0; inf < 4; inf++) {
  28454. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28455. if (weight <= 0)
  28456. break;
  28457. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28458. finalMatrix.addToSelf(tempMatrix);
  28459. }
  28460. }
  28461. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  28462. tempVector.toArray(data, index);
  28463. }
  28464. }
  28465. }
  28466. return data;
  28467. };
  28468. Mesh.prototype._createGlobalSubMesh = function (force) {
  28469. var totalVertices = this.getTotalVertices();
  28470. if (!totalVertices || !this.getIndices()) {
  28471. return null;
  28472. }
  28473. // Check if we need to recreate the submeshes
  28474. if (this.subMeshes && this.subMeshes.length > 0) {
  28475. var ib = this.getIndices();
  28476. if (!ib) {
  28477. return null;
  28478. }
  28479. var totalIndices = ib.length;
  28480. var needToRecreate = false;
  28481. if (force) {
  28482. needToRecreate = true;
  28483. }
  28484. else {
  28485. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28486. var submesh = _a[_i];
  28487. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  28488. needToRecreate = true;
  28489. break;
  28490. }
  28491. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  28492. needToRecreate = true;
  28493. break;
  28494. }
  28495. }
  28496. }
  28497. if (!needToRecreate) {
  28498. return this.subMeshes[0];
  28499. }
  28500. }
  28501. this.releaseSubMeshes();
  28502. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  28503. };
  28504. Mesh.prototype.subdivide = function (count) {
  28505. if (count < 1) {
  28506. return;
  28507. }
  28508. var totalIndices = this.getTotalIndices();
  28509. var subdivisionSize = (totalIndices / count) | 0;
  28510. var offset = 0;
  28511. // Ensure that subdivisionSize is a multiple of 3
  28512. while (subdivisionSize % 3 !== 0) {
  28513. subdivisionSize++;
  28514. }
  28515. this.releaseSubMeshes();
  28516. for (var index = 0; index < count; index++) {
  28517. if (offset >= totalIndices) {
  28518. break;
  28519. }
  28520. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  28521. offset += subdivisionSize;
  28522. }
  28523. this.synchronizeInstances();
  28524. };
  28525. /**
  28526. * Sets the vertex data of the mesh geometry for the requested `kind`.
  28527. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  28528. * The `data` are either a numeric array either a Float32Array.
  28529. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28530. * 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).
  28531. * Note that a new underlying VertexBuffer object is created each call.
  28532. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28533. *
  28534. * Possible `kind` values :
  28535. * - BABYLON.VertexBuffer.PositionKind
  28536. * - BABYLON.VertexBuffer.UVKind
  28537. * - BABYLON.VertexBuffer.UV2Kind
  28538. * - BABYLON.VertexBuffer.UV3Kind
  28539. * - BABYLON.VertexBuffer.UV4Kind
  28540. * - BABYLON.VertexBuffer.UV5Kind
  28541. * - BABYLON.VertexBuffer.UV6Kind
  28542. * - BABYLON.VertexBuffer.ColorKind
  28543. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28544. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28545. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28546. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28547. *
  28548. * Returns the Mesh.
  28549. */
  28550. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28551. if (updatable === void 0) { updatable = false; }
  28552. if (!this._geometry) {
  28553. var vertexData = new BABYLON.VertexData();
  28554. vertexData.set(data, kind);
  28555. var scene = this.getScene();
  28556. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28557. }
  28558. else {
  28559. this._geometry.setVerticesData(kind, data, updatable, stride);
  28560. }
  28561. return this;
  28562. };
  28563. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28564. if (updatable === void 0) { updatable = true; }
  28565. var vb = this.getVertexBuffer(kind);
  28566. if (!vb || vb.isUpdatable() === updatable) {
  28567. return;
  28568. }
  28569. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28570. };
  28571. /**
  28572. * Sets the mesh VertexBuffer.
  28573. * Returns the Mesh.
  28574. */
  28575. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28576. if (!this._geometry) {
  28577. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28578. }
  28579. this._geometry.setVerticesBuffer(buffer);
  28580. return this;
  28581. };
  28582. /**
  28583. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28584. * If the mesh has no geometry, it is simply returned as it is.
  28585. * The `data` are either a numeric array either a Float32Array.
  28586. * No new underlying VertexBuffer object is created.
  28587. * 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.
  28588. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28589. *
  28590. * Possible `kind` values :
  28591. * - BABYLON.VertexBuffer.PositionKind
  28592. * - BABYLON.VertexBuffer.UVKind
  28593. * - BABYLON.VertexBuffer.UV2Kind
  28594. * - BABYLON.VertexBuffer.UV3Kind
  28595. * - BABYLON.VertexBuffer.UV4Kind
  28596. * - BABYLON.VertexBuffer.UV5Kind
  28597. * - BABYLON.VertexBuffer.UV6Kind
  28598. * - BABYLON.VertexBuffer.ColorKind
  28599. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28600. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28601. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28602. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28603. *
  28604. * Returns the Mesh.
  28605. */
  28606. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28607. if (!this._geometry) {
  28608. return this;
  28609. }
  28610. if (!makeItUnique) {
  28611. this._geometry.updateVerticesData(kind, data, updateExtends);
  28612. }
  28613. else {
  28614. this.makeGeometryUnique();
  28615. this.updateVerticesData(kind, data, updateExtends, false);
  28616. }
  28617. return this;
  28618. };
  28619. /**
  28620. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28621. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28622. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28623. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28624. * Returns the Mesh.
  28625. */
  28626. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28627. if (computeNormals === void 0) { computeNormals = true; }
  28628. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28629. if (!positions) {
  28630. return this;
  28631. }
  28632. positionFunction(positions);
  28633. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28634. if (computeNormals) {
  28635. var indices = this.getIndices();
  28636. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28637. if (!normals) {
  28638. return this;
  28639. }
  28640. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28641. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28642. }
  28643. return this;
  28644. };
  28645. /**
  28646. * Creates a un-shared specific occurence of the geometry for the mesh.
  28647. * Returns the Mesh.
  28648. */
  28649. Mesh.prototype.makeGeometryUnique = function () {
  28650. if (!this._geometry) {
  28651. return this;
  28652. }
  28653. var oldGeometry = this._geometry;
  28654. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28655. oldGeometry.releaseForMesh(this, true);
  28656. geometry.applyToMesh(this);
  28657. return this;
  28658. };
  28659. /**
  28660. * Sets the mesh indices.
  28661. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28662. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28663. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28664. * This method creates a new index buffer each call.
  28665. * Returns the Mesh.
  28666. */
  28667. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28668. if (totalVertices === void 0) { totalVertices = null; }
  28669. if (updatable === void 0) { updatable = false; }
  28670. if (!this._geometry) {
  28671. var vertexData = new BABYLON.VertexData();
  28672. vertexData.indices = indices;
  28673. var scene = this.getScene();
  28674. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28675. }
  28676. else {
  28677. this._geometry.setIndices(indices, totalVertices, updatable);
  28678. }
  28679. return this;
  28680. };
  28681. /**
  28682. * Update the current index buffer
  28683. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28684. * Returns the Mesh.
  28685. */
  28686. Mesh.prototype.updateIndices = function (indices, offset) {
  28687. if (!this._geometry) {
  28688. return this;
  28689. }
  28690. this._geometry.updateIndices(indices, offset);
  28691. return this;
  28692. };
  28693. /**
  28694. * Invert the geometry to move from a right handed system to a left handed one.
  28695. * Returns the Mesh.
  28696. */
  28697. Mesh.prototype.toLeftHanded = function () {
  28698. if (!this._geometry) {
  28699. return this;
  28700. }
  28701. this._geometry.toLeftHanded();
  28702. return this;
  28703. };
  28704. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28705. if (!this._geometry) {
  28706. return this;
  28707. }
  28708. var engine = this.getScene().getEngine();
  28709. // Wireframe
  28710. var indexToBind;
  28711. if (this._unIndexed) {
  28712. indexToBind = null;
  28713. }
  28714. else {
  28715. switch (fillMode) {
  28716. case BABYLON.Material.PointFillMode:
  28717. indexToBind = null;
  28718. break;
  28719. case BABYLON.Material.WireFrameFillMode:
  28720. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28721. break;
  28722. default:
  28723. case BABYLON.Material.TriangleFillMode:
  28724. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28725. break;
  28726. }
  28727. }
  28728. // VBOs
  28729. this._geometry._bind(effect, indexToBind);
  28730. return this;
  28731. };
  28732. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28733. if (alternate === void 0) { alternate = false; }
  28734. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28735. return this;
  28736. }
  28737. this.onBeforeDrawObservable.notifyObservers(this);
  28738. var scene = this.getScene();
  28739. var engine = scene.getEngine();
  28740. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28741. // or triangles as points
  28742. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28743. }
  28744. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28745. // Triangles as wireframe
  28746. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28747. }
  28748. else {
  28749. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28750. }
  28751. if (scene._isAlternateRenderingEnabled && !alternate) {
  28752. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28753. if (!effect || !scene.activeCamera) {
  28754. return this;
  28755. }
  28756. scene._switchToAlternateCameraConfiguration(true);
  28757. this._effectiveMaterial.bindView(effect);
  28758. this._effectiveMaterial.bindViewProjection(effect);
  28759. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28760. this._draw(subMesh, fillMode, instancesCount, true);
  28761. engine.setViewport(scene.activeCamera.viewport);
  28762. scene._switchToAlternateCameraConfiguration(false);
  28763. this._effectiveMaterial.bindView(effect);
  28764. this._effectiveMaterial.bindViewProjection(effect);
  28765. }
  28766. return this;
  28767. };
  28768. /**
  28769. * Registers for this mesh a javascript function called just before the rendering process.
  28770. * This function is passed the current mesh.
  28771. * Return the Mesh.
  28772. */
  28773. Mesh.prototype.registerBeforeRender = function (func) {
  28774. this.onBeforeRenderObservable.add(func);
  28775. return this;
  28776. };
  28777. /**
  28778. * Disposes a previously registered javascript function called before the rendering.
  28779. * This function is passed the current mesh.
  28780. * Returns the Mesh.
  28781. */
  28782. Mesh.prototype.unregisterBeforeRender = function (func) {
  28783. this.onBeforeRenderObservable.removeCallback(func);
  28784. return this;
  28785. };
  28786. /**
  28787. * Registers for this mesh a javascript function called just after the rendering is complete.
  28788. * This function is passed the current mesh.
  28789. * Returns the Mesh.
  28790. */
  28791. Mesh.prototype.registerAfterRender = function (func) {
  28792. this.onAfterRenderObservable.add(func);
  28793. return this;
  28794. };
  28795. /**
  28796. * Disposes a previously registered javascript function called after the rendering.
  28797. * This function is passed the current mesh.
  28798. * Return the Mesh.
  28799. */
  28800. Mesh.prototype.unregisterAfterRender = function (func) {
  28801. this.onAfterRenderObservable.removeCallback(func);
  28802. return this;
  28803. };
  28804. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28805. var scene = this.getScene();
  28806. this._batchCache.mustReturn = false;
  28807. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28808. this._batchCache.visibleInstances[subMeshId] = null;
  28809. if (this._visibleInstances) {
  28810. var currentRenderId = scene.getRenderId();
  28811. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28812. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28813. var selfRenderId = this._renderId;
  28814. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28815. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28816. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28817. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28818. }
  28819. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28820. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28821. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28822. this._batchCache.mustReturn = true;
  28823. return this._batchCache;
  28824. }
  28825. if (currentRenderId !== selfRenderId) {
  28826. this._batchCache.renderSelf[subMeshId] = false;
  28827. }
  28828. }
  28829. this._renderIdForInstances[subMeshId] = currentRenderId;
  28830. }
  28831. return this._batchCache;
  28832. };
  28833. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28834. var visibleInstances = batch.visibleInstances[subMesh._id];
  28835. if (!visibleInstances) {
  28836. return this;
  28837. }
  28838. var matricesCount = visibleInstances.length + 1;
  28839. var bufferSize = matricesCount * 16 * 4;
  28840. var currentInstancesBufferSize = this._instancesBufferSize;
  28841. var instancesBuffer = this._instancesBuffer;
  28842. while (this._instancesBufferSize < bufferSize) {
  28843. this._instancesBufferSize *= 2;
  28844. }
  28845. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28846. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28847. }
  28848. var offset = 0;
  28849. var instancesCount = 0;
  28850. var world = this.getWorldMatrix();
  28851. if (batch.renderSelf[subMesh._id]) {
  28852. world.copyToArray(this._instancesData, offset);
  28853. offset += 16;
  28854. instancesCount++;
  28855. }
  28856. if (visibleInstances) {
  28857. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28858. var instance = visibleInstances[instanceIndex];
  28859. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28860. offset += 16;
  28861. instancesCount++;
  28862. }
  28863. }
  28864. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28865. if (instancesBuffer) {
  28866. instancesBuffer.dispose();
  28867. }
  28868. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28869. this._instancesBuffer = instancesBuffer;
  28870. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28871. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28872. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28873. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28874. }
  28875. else {
  28876. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28877. }
  28878. this._bind(subMesh, effect, fillMode);
  28879. this._draw(subMesh, fillMode, instancesCount);
  28880. engine.unbindInstanceAttributes();
  28881. return this;
  28882. };
  28883. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28884. var scene = this.getScene();
  28885. var engine = scene.getEngine();
  28886. if (hardwareInstancedRendering) {
  28887. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28888. }
  28889. else {
  28890. if (batch.renderSelf[subMesh._id]) {
  28891. // Draw
  28892. if (onBeforeDraw) {
  28893. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28894. }
  28895. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28896. }
  28897. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28898. if (visibleInstancesForSubMesh) {
  28899. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28900. var instance = visibleInstancesForSubMesh[instanceIndex];
  28901. // World
  28902. var world = instance.getWorldMatrix();
  28903. if (onBeforeDraw) {
  28904. onBeforeDraw(true, world, effectiveMaterial);
  28905. }
  28906. // Draw
  28907. this._draw(subMesh, fillMode);
  28908. }
  28909. }
  28910. }
  28911. return this;
  28912. };
  28913. /**
  28914. * Triggers the draw call for the mesh.
  28915. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28916. * Returns the Mesh.
  28917. */
  28918. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28919. this.checkOcclusionQuery();
  28920. if (this._isOccluded) {
  28921. return this;
  28922. }
  28923. var scene = this.getScene();
  28924. // Managing instances
  28925. var batch = this._getInstancesRenderList(subMesh._id);
  28926. if (batch.mustReturn) {
  28927. return this;
  28928. }
  28929. // Checking geometry state
  28930. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28931. return this;
  28932. }
  28933. this.onBeforeRenderObservable.notifyObservers(this);
  28934. var engine = scene.getEngine();
  28935. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28936. // Material
  28937. var material = subMesh.getMaterial();
  28938. if (!material) {
  28939. return this;
  28940. }
  28941. this._effectiveMaterial = material;
  28942. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28943. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28944. return this;
  28945. }
  28946. }
  28947. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28948. return this;
  28949. }
  28950. // Alpha mode
  28951. if (enableAlphaMode) {
  28952. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28953. }
  28954. // Outline - step 1
  28955. var savedDepthWrite = engine.getDepthWrite();
  28956. if (this.renderOutline) {
  28957. engine.setDepthWrite(false);
  28958. scene.getOutlineRenderer().render(subMesh, batch);
  28959. engine.setDepthWrite(savedDepthWrite);
  28960. }
  28961. var effect;
  28962. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28963. effect = subMesh.effect;
  28964. }
  28965. else {
  28966. effect = this._effectiveMaterial.getEffect();
  28967. }
  28968. if (!effect) {
  28969. return this;
  28970. }
  28971. var sideOrientation = this.overrideMaterialSideOrientation;
  28972. if (sideOrientation == null) {
  28973. sideOrientation = this._effectiveMaterial.sideOrientation;
  28974. if (this._getWorldMatrixDeterminant() < 0) {
  28975. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28976. }
  28977. }
  28978. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  28979. if (this._effectiveMaterial.forceDepthWrite) {
  28980. engine.setDepthWrite(true);
  28981. }
  28982. // Bind
  28983. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  28984. if (!hardwareInstancedRendering) {
  28985. this._bind(subMesh, effect, fillMode);
  28986. }
  28987. var world = this.getWorldMatrix();
  28988. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28989. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  28990. }
  28991. else {
  28992. this._effectiveMaterial.bind(world, this);
  28993. }
  28994. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  28995. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  28996. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28997. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  28998. }
  28999. // Draw
  29000. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  29001. // Unbind
  29002. this._effectiveMaterial.unbind();
  29003. // Outline - step 2
  29004. if (this.renderOutline && savedDepthWrite) {
  29005. engine.setDepthWrite(true);
  29006. engine.setColorWrite(false);
  29007. scene.getOutlineRenderer().render(subMesh, batch);
  29008. engine.setColorWrite(true);
  29009. }
  29010. // Overlay
  29011. if (this.renderOverlay) {
  29012. var currentMode = engine.getAlphaMode();
  29013. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  29014. scene.getOutlineRenderer().render(subMesh, batch, true);
  29015. engine.setAlphaMode(currentMode);
  29016. }
  29017. this.onAfterRenderObservable.notifyObservers(this);
  29018. return this;
  29019. };
  29020. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  29021. if (isInstance && effectiveMaterial) {
  29022. effectiveMaterial.bindOnlyWorldMatrix(world);
  29023. }
  29024. };
  29025. /**
  29026. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  29027. */
  29028. Mesh.prototype.getEmittedParticleSystems = function () {
  29029. var results = new Array();
  29030. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29031. var particleSystem = this.getScene().particleSystems[index];
  29032. if (particleSystem.emitter === this) {
  29033. results.push(particleSystem);
  29034. }
  29035. }
  29036. return results;
  29037. };
  29038. /**
  29039. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  29040. */
  29041. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  29042. var results = new Array();
  29043. var descendants = this.getDescendants();
  29044. descendants.push(this);
  29045. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29046. var particleSystem = this.getScene().particleSystems[index];
  29047. var emitter = particleSystem.emitter;
  29048. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  29049. results.push(particleSystem);
  29050. }
  29051. }
  29052. return results;
  29053. };
  29054. Mesh.prototype._checkDelayState = function () {
  29055. var scene = this.getScene();
  29056. if (this._geometry) {
  29057. this._geometry.load(scene);
  29058. }
  29059. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29060. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29061. this._queueLoad(scene);
  29062. }
  29063. return this;
  29064. };
  29065. Mesh.prototype._queueLoad = function (scene) {
  29066. var _this = this;
  29067. scene._addPendingData(this);
  29068. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  29069. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29070. if (data instanceof ArrayBuffer) {
  29071. _this._delayLoadingFunction(data, _this);
  29072. }
  29073. else {
  29074. _this._delayLoadingFunction(JSON.parse(data), _this);
  29075. }
  29076. _this.instances.forEach(function (instance) {
  29077. instance._syncSubMeshes();
  29078. });
  29079. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29080. scene._removePendingData(_this);
  29081. }, function () { }, scene.database, getBinaryData);
  29082. return this;
  29083. };
  29084. /**
  29085. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  29086. */
  29087. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  29088. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29089. return false;
  29090. }
  29091. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  29092. return false;
  29093. }
  29094. this._checkDelayState();
  29095. return true;
  29096. };
  29097. /**
  29098. * Sets the mesh material by the material or multiMaterial `id` property.
  29099. * The material `id` is a string identifying the material or the multiMaterial.
  29100. * This method returns the Mesh.
  29101. */
  29102. Mesh.prototype.setMaterialByID = function (id) {
  29103. var materials = this.getScene().materials;
  29104. var index;
  29105. for (index = materials.length - 1; index > -1; index--) {
  29106. if (materials[index].id === id) {
  29107. this.material = materials[index];
  29108. return this;
  29109. }
  29110. }
  29111. // Multi
  29112. var multiMaterials = this.getScene().multiMaterials;
  29113. for (index = multiMaterials.length - 1; index > -1; index--) {
  29114. if (multiMaterials[index].id === id) {
  29115. this.material = multiMaterials[index];
  29116. return this;
  29117. }
  29118. }
  29119. return this;
  29120. };
  29121. /**
  29122. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  29123. */
  29124. Mesh.prototype.getAnimatables = function () {
  29125. var results = new Array();
  29126. if (this.material) {
  29127. results.push(this.material);
  29128. }
  29129. if (this.skeleton) {
  29130. results.push(this.skeleton);
  29131. }
  29132. return results;
  29133. };
  29134. /**
  29135. * Modifies the mesh geometry according to the passed transformation matrix.
  29136. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  29137. * The mesh normals are modified accordingly the same transformation.
  29138. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  29139. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29140. * Returns the Mesh.
  29141. */
  29142. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  29143. // Position
  29144. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29145. return this;
  29146. }
  29147. var submeshes = this.subMeshes.splice(0);
  29148. this._resetPointsArrayCache();
  29149. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29150. var temp = new Array();
  29151. var index;
  29152. for (index = 0; index < data.length; index += 3) {
  29153. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  29154. }
  29155. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  29156. // Normals
  29157. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29158. return this;
  29159. }
  29160. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29161. temp = [];
  29162. for (index = 0; index < data.length; index += 3) {
  29163. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  29164. }
  29165. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  29166. // flip faces?
  29167. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  29168. this.flipFaces();
  29169. }
  29170. // Restore submeshes
  29171. this.releaseSubMeshes();
  29172. this.subMeshes = submeshes;
  29173. return this;
  29174. };
  29175. /**
  29176. * Modifies the mesh geometry according to its own current World Matrix.
  29177. * The mesh World Matrix is then reset.
  29178. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  29179. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  29180. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29181. * Returns the Mesh.
  29182. */
  29183. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  29184. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  29185. this.scaling.copyFromFloats(1, 1, 1);
  29186. this.position.copyFromFloats(0, 0, 0);
  29187. this.rotation.copyFromFloats(0, 0, 0);
  29188. //only if quaternion is already set
  29189. if (this.rotationQuaternion) {
  29190. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  29191. }
  29192. this._worldMatrix = BABYLON.Matrix.Identity();
  29193. return this;
  29194. };
  29195. Object.defineProperty(Mesh.prototype, "_positions", {
  29196. // Cache
  29197. get: function () {
  29198. if (this._geometry) {
  29199. return this._geometry._positions;
  29200. }
  29201. return null;
  29202. },
  29203. enumerable: true,
  29204. configurable: true
  29205. });
  29206. Mesh.prototype._resetPointsArrayCache = function () {
  29207. if (this._geometry) {
  29208. this._geometry._resetPointsArrayCache();
  29209. }
  29210. return this;
  29211. };
  29212. Mesh.prototype._generatePointsArray = function () {
  29213. if (this._geometry) {
  29214. return this._geometry._generatePointsArray();
  29215. }
  29216. return false;
  29217. };
  29218. /**
  29219. * Returns a new Mesh object generated from the current mesh properties.
  29220. * This method must not get confused with createInstance().
  29221. * The parameter `name` is a string, the name given to the new mesh.
  29222. * The optional parameter `newParent` can be any Node object (default `null`).
  29223. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  29224. * 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.
  29225. */
  29226. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  29227. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  29228. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  29229. };
  29230. /**
  29231. * Releases resources associated with this mesh.
  29232. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  29233. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  29234. */
  29235. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  29236. var _this = this;
  29237. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  29238. this.morphTargetManager = null;
  29239. if (this._geometry) {
  29240. this._geometry.releaseForMesh(this, true);
  29241. }
  29242. // Sources
  29243. var meshes = this.getScene().meshes;
  29244. meshes.forEach(function (abstractMesh) {
  29245. var mesh = abstractMesh;
  29246. if (mesh._source && mesh._source === _this) {
  29247. mesh._source = null;
  29248. }
  29249. });
  29250. this._source = null;
  29251. // Instances
  29252. if (this._instancesBuffer) {
  29253. this._instancesBuffer.dispose();
  29254. this._instancesBuffer = null;
  29255. }
  29256. while (this.instances.length) {
  29257. this.instances[0].dispose();
  29258. }
  29259. // Effect layers.
  29260. var effectLayers = this.getScene().effectLayers;
  29261. for (var i = 0; i < effectLayers.length; i++) {
  29262. var effectLayer = effectLayers[i];
  29263. if (effectLayer) {
  29264. effectLayer._disposeMesh(this);
  29265. }
  29266. }
  29267. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  29268. };
  29269. /**
  29270. * Modifies the mesh geometry according to a displacement map.
  29271. * 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.
  29272. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29273. * This method returns nothing.
  29274. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  29275. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29276. * 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.
  29277. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29278. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29279. *
  29280. * Returns the Mesh.
  29281. */
  29282. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  29283. var _this = this;
  29284. var scene = this.getScene();
  29285. var onload = function (img) {
  29286. // Getting height map data
  29287. var canvas = document.createElement("canvas");
  29288. var context = canvas.getContext("2d");
  29289. var heightMapWidth = img.width;
  29290. var heightMapHeight = img.height;
  29291. canvas.width = heightMapWidth;
  29292. canvas.height = heightMapHeight;
  29293. context.drawImage(img, 0, 0);
  29294. // Create VertexData from map data
  29295. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  29296. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  29297. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  29298. //execute success callback, if set
  29299. if (onSuccess) {
  29300. onSuccess(_this);
  29301. }
  29302. };
  29303. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  29304. return this;
  29305. };
  29306. /**
  29307. * Modifies the mesh geometry according to a displacementMap buffer.
  29308. * 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.
  29309. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29310. * This method returns nothing.
  29311. * 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.
  29312. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  29313. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29314. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29315. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29316. *
  29317. * Returns the Mesh.
  29318. */
  29319. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  29320. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  29321. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  29322. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29323. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  29324. return this;
  29325. }
  29326. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29327. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29328. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29329. var position = BABYLON.Vector3.Zero();
  29330. var normal = BABYLON.Vector3.Zero();
  29331. var uv = BABYLON.Vector2.Zero();
  29332. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  29333. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  29334. for (var index = 0; index < positions.length; index += 3) {
  29335. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  29336. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  29337. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  29338. // Compute height
  29339. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  29340. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  29341. var pos = (u + v * heightMapWidth) * 4;
  29342. var r = buffer[pos] / 255.0;
  29343. var g = buffer[pos + 1] / 255.0;
  29344. var b = buffer[pos + 2] / 255.0;
  29345. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  29346. normal.normalize();
  29347. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  29348. position = position.add(normal);
  29349. position.toArray(positions, index);
  29350. }
  29351. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  29352. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  29353. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  29354. return this;
  29355. };
  29356. /**
  29357. * Modify the mesh to get a flat shading rendering.
  29358. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  29359. * This method returns the Mesh.
  29360. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  29361. */
  29362. Mesh.prototype.convertToFlatShadedMesh = function () {
  29363. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  29364. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29365. var kinds = this.getVerticesDataKinds();
  29366. var vbs = {};
  29367. var data = {};
  29368. var newdata = {};
  29369. var updatableNormals = false;
  29370. var kindIndex;
  29371. var kind;
  29372. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29373. kind = kinds[kindIndex];
  29374. var vertexBuffer = this.getVertexBuffer(kind);
  29375. if (kind === BABYLON.VertexBuffer.NormalKind) {
  29376. updatableNormals = vertexBuffer.isUpdatable();
  29377. kinds.splice(kindIndex, 1);
  29378. kindIndex--;
  29379. continue;
  29380. }
  29381. vbs[kind] = vertexBuffer;
  29382. data[kind] = vbs[kind].getData();
  29383. newdata[kind] = [];
  29384. }
  29385. // Save previous submeshes
  29386. var previousSubmeshes = this.subMeshes.slice(0);
  29387. var indices = this.getIndices();
  29388. var totalIndices = this.getTotalIndices();
  29389. // Generating unique vertices per face
  29390. var index;
  29391. for (index = 0; index < totalIndices; index++) {
  29392. var vertexIndex = indices[index];
  29393. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29394. kind = kinds[kindIndex];
  29395. var stride = vbs[kind].getStrideSize();
  29396. for (var offset = 0; offset < stride; offset++) {
  29397. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29398. }
  29399. }
  29400. }
  29401. // Updating faces & normal
  29402. var normals = [];
  29403. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  29404. for (index = 0; index < totalIndices; index += 3) {
  29405. indices[index] = index;
  29406. indices[index + 1] = index + 1;
  29407. indices[index + 2] = index + 2;
  29408. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  29409. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  29410. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  29411. var p1p2 = p1.subtract(p2);
  29412. var p3p2 = p3.subtract(p2);
  29413. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  29414. // Store same normals for every vertex
  29415. for (var localIndex = 0; localIndex < 3; localIndex++) {
  29416. normals.push(normal.x);
  29417. normals.push(normal.y);
  29418. normals.push(normal.z);
  29419. }
  29420. }
  29421. this.setIndices(indices);
  29422. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  29423. // Updating vertex buffers
  29424. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29425. kind = kinds[kindIndex];
  29426. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29427. }
  29428. // Updating submeshes
  29429. this.releaseSubMeshes();
  29430. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29431. var previousOne = previousSubmeshes[submeshIndex];
  29432. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29433. }
  29434. this.synchronizeInstances();
  29435. return this;
  29436. };
  29437. /**
  29438. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  29439. * In other words, more vertices, no more indices and a single bigger VBO.
  29440. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  29441. * Returns the Mesh.
  29442. */
  29443. Mesh.prototype.convertToUnIndexedMesh = function () {
  29444. /// <summary>Remove indices by unfolding faces into buffers</summary>
  29445. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29446. var kinds = this.getVerticesDataKinds();
  29447. var vbs = {};
  29448. var data = {};
  29449. var newdata = {};
  29450. var kindIndex;
  29451. var kind;
  29452. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29453. kind = kinds[kindIndex];
  29454. var vertexBuffer = this.getVertexBuffer(kind);
  29455. vbs[kind] = vertexBuffer;
  29456. data[kind] = vbs[kind].getData();
  29457. newdata[kind] = [];
  29458. }
  29459. // Save previous submeshes
  29460. var previousSubmeshes = this.subMeshes.slice(0);
  29461. var indices = this.getIndices();
  29462. var totalIndices = this.getTotalIndices();
  29463. // Generating unique vertices per face
  29464. var index;
  29465. for (index = 0; index < totalIndices; index++) {
  29466. var vertexIndex = indices[index];
  29467. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29468. kind = kinds[kindIndex];
  29469. var stride = vbs[kind].getStrideSize();
  29470. for (var offset = 0; offset < stride; offset++) {
  29471. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29472. }
  29473. }
  29474. }
  29475. // Updating indices
  29476. for (index = 0; index < totalIndices; index += 3) {
  29477. indices[index] = index;
  29478. indices[index + 1] = index + 1;
  29479. indices[index + 2] = index + 2;
  29480. }
  29481. this.setIndices(indices);
  29482. // Updating vertex buffers
  29483. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29484. kind = kinds[kindIndex];
  29485. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29486. }
  29487. // Updating submeshes
  29488. this.releaseSubMeshes();
  29489. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29490. var previousOne = previousSubmeshes[submeshIndex];
  29491. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29492. }
  29493. this._unIndexed = true;
  29494. this.synchronizeInstances();
  29495. return this;
  29496. };
  29497. /**
  29498. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  29499. * This method returns the Mesh.
  29500. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  29501. */
  29502. Mesh.prototype.flipFaces = function (flipNormals) {
  29503. if (flipNormals === void 0) { flipNormals = false; }
  29504. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  29505. var i;
  29506. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  29507. for (i = 0; i < vertex_data.normals.length; i++) {
  29508. vertex_data.normals[i] *= -1;
  29509. }
  29510. }
  29511. if (vertex_data.indices) {
  29512. var temp;
  29513. for (i = 0; i < vertex_data.indices.length; i += 3) {
  29514. // reassign indices
  29515. temp = vertex_data.indices[i + 1];
  29516. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  29517. vertex_data.indices[i + 2] = temp;
  29518. }
  29519. }
  29520. vertex_data.applyToMesh(this);
  29521. return this;
  29522. };
  29523. // Instances
  29524. /**
  29525. * Creates a new InstancedMesh object from the mesh model.
  29526. * An instance shares the same properties and the same material than its model.
  29527. * Only these properties of each instance can then be set individually :
  29528. * - position
  29529. * - rotation
  29530. * - rotationQuaternion
  29531. * - setPivotMatrix
  29532. * - scaling
  29533. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29534. * Warning : this method is not supported for Line mesh and LineSystem
  29535. */
  29536. Mesh.prototype.createInstance = function (name) {
  29537. return new BABYLON.InstancedMesh(name, this);
  29538. };
  29539. /**
  29540. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29541. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29542. * This method returns the Mesh.
  29543. */
  29544. Mesh.prototype.synchronizeInstances = function () {
  29545. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29546. var instance = this.instances[instanceIndex];
  29547. instance._syncSubMeshes();
  29548. }
  29549. return this;
  29550. };
  29551. /**
  29552. * Simplify the mesh according to the given array of settings.
  29553. * Function will return immediately and will simplify async. It returns the Mesh.
  29554. * @param settings a collection of simplification settings.
  29555. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29556. * @param type the type of simplification to run.
  29557. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29558. */
  29559. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29560. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29561. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29562. this.getScene().simplificationQueue.addTask({
  29563. settings: settings,
  29564. parallelProcessing: parallelProcessing,
  29565. mesh: this,
  29566. simplificationType: simplificationType,
  29567. successCallback: successCallback
  29568. });
  29569. return this;
  29570. };
  29571. /**
  29572. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29573. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29574. * This should be used together with the simplification to avoid disappearing triangles.
  29575. * Returns the Mesh.
  29576. * @param successCallback an optional success callback to be called after the optimization finished.
  29577. */
  29578. Mesh.prototype.optimizeIndices = function (successCallback) {
  29579. var _this = this;
  29580. var indices = this.getIndices();
  29581. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29582. if (!positions || !indices) {
  29583. return this;
  29584. }
  29585. var vectorPositions = new Array();
  29586. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29587. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29588. }
  29589. var dupes = new Array();
  29590. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29591. var realPos = vectorPositions.length - 1 - iteration;
  29592. var testedPosition = vectorPositions[realPos];
  29593. for (var j = 0; j < realPos; ++j) {
  29594. var againstPosition = vectorPositions[j];
  29595. if (testedPosition.equals(againstPosition)) {
  29596. dupes[realPos] = j;
  29597. break;
  29598. }
  29599. }
  29600. }, function () {
  29601. for (var i = 0; i < indices.length; ++i) {
  29602. indices[i] = dupes[indices[i]] || indices[i];
  29603. }
  29604. //indices are now reordered
  29605. var originalSubMeshes = _this.subMeshes.slice(0);
  29606. _this.setIndices(indices);
  29607. _this.subMeshes = originalSubMeshes;
  29608. if (successCallback) {
  29609. successCallback(_this);
  29610. }
  29611. });
  29612. return this;
  29613. };
  29614. Mesh.prototype.serialize = function (serializationObject) {
  29615. serializationObject.name = this.name;
  29616. serializationObject.id = this.id;
  29617. serializationObject.type = this.getClassName();
  29618. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29619. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29620. }
  29621. serializationObject.position = this.position.asArray();
  29622. if (this.rotationQuaternion) {
  29623. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29624. }
  29625. else if (this.rotation) {
  29626. serializationObject.rotation = this.rotation.asArray();
  29627. }
  29628. serializationObject.scaling = this.scaling.asArray();
  29629. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29630. serializationObject.isEnabled = this.isEnabled(false);
  29631. serializationObject.isVisible = this.isVisible;
  29632. serializationObject.infiniteDistance = this.infiniteDistance;
  29633. serializationObject.pickable = this.isPickable;
  29634. serializationObject.receiveShadows = this.receiveShadows;
  29635. serializationObject.billboardMode = this.billboardMode;
  29636. serializationObject.visibility = this.visibility;
  29637. serializationObject.checkCollisions = this.checkCollisions;
  29638. serializationObject.isBlocker = this.isBlocker;
  29639. // Parent
  29640. if (this.parent) {
  29641. serializationObject.parentId = this.parent.id;
  29642. }
  29643. // Geometry
  29644. serializationObject.isUnIndexed = this.isUnIndexed;
  29645. var geometry = this._geometry;
  29646. if (geometry) {
  29647. var geometryId = geometry.id;
  29648. serializationObject.geometryId = geometryId;
  29649. // SubMeshes
  29650. serializationObject.subMeshes = [];
  29651. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29652. var subMesh = this.subMeshes[subIndex];
  29653. serializationObject.subMeshes.push({
  29654. materialIndex: subMesh.materialIndex,
  29655. verticesStart: subMesh.verticesStart,
  29656. verticesCount: subMesh.verticesCount,
  29657. indexStart: subMesh.indexStart,
  29658. indexCount: subMesh.indexCount
  29659. });
  29660. }
  29661. }
  29662. // Material
  29663. if (this.material) {
  29664. serializationObject.materialId = this.material.id;
  29665. }
  29666. else {
  29667. this.material = null;
  29668. }
  29669. // Morph targets
  29670. if (this.morphTargetManager) {
  29671. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29672. }
  29673. // Skeleton
  29674. if (this.skeleton) {
  29675. serializationObject.skeletonId = this.skeleton.id;
  29676. }
  29677. // Physics
  29678. //TODO implement correct serialization for physics impostors.
  29679. var impostor = this.getPhysicsImpostor();
  29680. if (impostor) {
  29681. serializationObject.physicsMass = impostor.getParam("mass");
  29682. serializationObject.physicsFriction = impostor.getParam("friction");
  29683. serializationObject.physicsRestitution = impostor.getParam("mass");
  29684. serializationObject.physicsImpostor = impostor.type;
  29685. }
  29686. // Metadata
  29687. if (this.metadata) {
  29688. serializationObject.metadata = this.metadata;
  29689. }
  29690. // Instances
  29691. serializationObject.instances = [];
  29692. for (var index = 0; index < this.instances.length; index++) {
  29693. var instance = this.instances[index];
  29694. var serializationInstance = {
  29695. name: instance.name,
  29696. id: instance.id,
  29697. position: instance.position.asArray(),
  29698. scaling: instance.scaling.asArray()
  29699. };
  29700. if (instance.rotationQuaternion) {
  29701. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29702. }
  29703. else if (instance.rotation) {
  29704. serializationInstance.rotation = instance.rotation.asArray();
  29705. }
  29706. serializationObject.instances.push(serializationInstance);
  29707. // Animations
  29708. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29709. serializationInstance.ranges = instance.serializeAnimationRanges();
  29710. }
  29711. //
  29712. // Animations
  29713. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29714. serializationObject.ranges = this.serializeAnimationRanges();
  29715. // Layer mask
  29716. serializationObject.layerMask = this.layerMask;
  29717. // Alpha
  29718. serializationObject.alphaIndex = this.alphaIndex;
  29719. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29720. // Overlay
  29721. serializationObject.overlayAlpha = this.overlayAlpha;
  29722. serializationObject.overlayColor = this.overlayColor.asArray();
  29723. serializationObject.renderOverlay = this.renderOverlay;
  29724. // Fog
  29725. serializationObject.applyFog = this.applyFog;
  29726. // Action Manager
  29727. if (this.actionManager) {
  29728. serializationObject.actions = this.actionManager.serialize(this.name);
  29729. }
  29730. };
  29731. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29732. if (!this.geometry) {
  29733. return;
  29734. }
  29735. this._markSubMeshesAsAttributesDirty();
  29736. var morphTargetManager = this._morphTargetManager;
  29737. if (morphTargetManager && morphTargetManager.vertexCount) {
  29738. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29739. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29740. this.morphTargetManager = null;
  29741. return;
  29742. }
  29743. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29744. var morphTarget = morphTargetManager.getActiveTarget(index);
  29745. var positions = morphTarget.getPositions();
  29746. if (!positions) {
  29747. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29748. return;
  29749. }
  29750. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29751. var normals = morphTarget.getNormals();
  29752. if (normals) {
  29753. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29754. }
  29755. var tangents = morphTarget.getTangents();
  29756. if (tangents) {
  29757. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29758. }
  29759. }
  29760. }
  29761. else {
  29762. var index = 0;
  29763. // Positions
  29764. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29765. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29766. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29767. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29768. }
  29769. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29770. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29771. }
  29772. index++;
  29773. }
  29774. }
  29775. };
  29776. // Statics
  29777. /**
  29778. * Returns a new Mesh object parsed from the source provided.
  29779. * The parameter `parsedMesh` is the source.
  29780. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29781. */
  29782. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29783. var mesh;
  29784. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29785. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29786. }
  29787. else {
  29788. mesh = new Mesh(parsedMesh.name, scene);
  29789. }
  29790. mesh.id = parsedMesh.id;
  29791. if (BABYLON.Tags) {
  29792. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29793. }
  29794. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29795. if (parsedMesh.metadata !== undefined) {
  29796. mesh.metadata = parsedMesh.metadata;
  29797. }
  29798. if (parsedMesh.rotationQuaternion) {
  29799. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29800. }
  29801. else if (parsedMesh.rotation) {
  29802. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29803. }
  29804. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29805. if (parsedMesh.localMatrix) {
  29806. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29807. }
  29808. else if (parsedMesh.pivotMatrix) {
  29809. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29810. }
  29811. mesh.setEnabled(parsedMesh.isEnabled);
  29812. mesh.isVisible = parsedMesh.isVisible;
  29813. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29814. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29815. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29816. if (parsedMesh.applyFog !== undefined) {
  29817. mesh.applyFog = parsedMesh.applyFog;
  29818. }
  29819. if (parsedMesh.pickable !== undefined) {
  29820. mesh.isPickable = parsedMesh.pickable;
  29821. }
  29822. if (parsedMesh.alphaIndex !== undefined) {
  29823. mesh.alphaIndex = parsedMesh.alphaIndex;
  29824. }
  29825. mesh.receiveShadows = parsedMesh.receiveShadows;
  29826. mesh.billboardMode = parsedMesh.billboardMode;
  29827. if (parsedMesh.visibility !== undefined) {
  29828. mesh.visibility = parsedMesh.visibility;
  29829. }
  29830. mesh.checkCollisions = parsedMesh.checkCollisions;
  29831. if (parsedMesh.isBlocker !== undefined) {
  29832. mesh.isBlocker = parsedMesh.isBlocker;
  29833. }
  29834. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29835. // freezeWorldMatrix
  29836. if (parsedMesh.freezeWorldMatrix) {
  29837. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29838. }
  29839. // Parent
  29840. if (parsedMesh.parentId) {
  29841. mesh._waitingParentId = parsedMesh.parentId;
  29842. }
  29843. // Actions
  29844. if (parsedMesh.actions !== undefined) {
  29845. mesh._waitingActions = parsedMesh.actions;
  29846. }
  29847. // Overlay
  29848. if (parsedMesh.overlayAlpha !== undefined) {
  29849. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29850. }
  29851. if (parsedMesh.overlayColor !== undefined) {
  29852. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29853. }
  29854. if (parsedMesh.renderOverlay !== undefined) {
  29855. mesh.renderOverlay = parsedMesh.renderOverlay;
  29856. }
  29857. // Geometry
  29858. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29859. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29860. if (parsedMesh.delayLoadingFile) {
  29861. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29862. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29863. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29864. if (parsedMesh._binaryInfo) {
  29865. mesh._binaryInfo = parsedMesh._binaryInfo;
  29866. }
  29867. mesh._delayInfo = [];
  29868. if (parsedMesh.hasUVs) {
  29869. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29870. }
  29871. if (parsedMesh.hasUVs2) {
  29872. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29873. }
  29874. if (parsedMesh.hasUVs3) {
  29875. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29876. }
  29877. if (parsedMesh.hasUVs4) {
  29878. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29879. }
  29880. if (parsedMesh.hasUVs5) {
  29881. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29882. }
  29883. if (parsedMesh.hasUVs6) {
  29884. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29885. }
  29886. if (parsedMesh.hasColors) {
  29887. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29888. }
  29889. if (parsedMesh.hasMatricesIndices) {
  29890. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29891. }
  29892. if (parsedMesh.hasMatricesWeights) {
  29893. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29894. }
  29895. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29896. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29897. mesh._checkDelayState();
  29898. }
  29899. }
  29900. else {
  29901. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29902. }
  29903. // Material
  29904. if (parsedMesh.materialId) {
  29905. mesh.setMaterialByID(parsedMesh.materialId);
  29906. }
  29907. else {
  29908. mesh.material = null;
  29909. }
  29910. // Morph targets
  29911. if (parsedMesh.morphTargetManagerId > -1) {
  29912. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29913. }
  29914. // Skeleton
  29915. if (parsedMesh.skeletonId > -1) {
  29916. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29917. if (parsedMesh.numBoneInfluencers) {
  29918. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29919. }
  29920. }
  29921. // Animations
  29922. if (parsedMesh.animations) {
  29923. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29924. var parsedAnimation = parsedMesh.animations[animationIndex];
  29925. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29926. }
  29927. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29928. }
  29929. if (parsedMesh.autoAnimate) {
  29930. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29931. }
  29932. // Layer Mask
  29933. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29934. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29935. }
  29936. else {
  29937. mesh.layerMask = 0x0FFFFFFF;
  29938. }
  29939. // Physics
  29940. if (parsedMesh.physicsImpostor) {
  29941. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29942. mass: parsedMesh.physicsMass,
  29943. friction: parsedMesh.physicsFriction,
  29944. restitution: parsedMesh.physicsRestitution
  29945. }, scene);
  29946. }
  29947. // Instances
  29948. if (parsedMesh.instances) {
  29949. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29950. var parsedInstance = parsedMesh.instances[index];
  29951. var instance = mesh.createInstance(parsedInstance.name);
  29952. if (parsedInstance.id) {
  29953. instance.id = parsedInstance.id;
  29954. }
  29955. if (BABYLON.Tags) {
  29956. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29957. }
  29958. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29959. if (parsedInstance.parentId) {
  29960. instance._waitingParentId = parsedInstance.parentId;
  29961. }
  29962. if (parsedInstance.rotationQuaternion) {
  29963. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29964. }
  29965. else if (parsedInstance.rotation) {
  29966. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29967. }
  29968. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29969. instance.checkCollisions = mesh.checkCollisions;
  29970. if (parsedMesh.animations) {
  29971. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29972. parsedAnimation = parsedMesh.animations[animationIndex];
  29973. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29974. }
  29975. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29976. }
  29977. }
  29978. }
  29979. return mesh;
  29980. };
  29981. /**
  29982. * Creates a ribbon mesh.
  29983. * Please consider using the same method from the MeshBuilder class instead.
  29984. * 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.
  29985. *
  29986. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  29987. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  29988. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  29989. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  29990. * 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.
  29991. * 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.
  29992. * 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
  29993. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29994. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29995. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29996. */
  29997. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  29998. if (closeArray === void 0) { closeArray = false; }
  29999. if (updatable === void 0) { updatable = false; }
  30000. return BABYLON.MeshBuilder.CreateRibbon(name, {
  30001. pathArray: pathArray,
  30002. closeArray: closeArray,
  30003. closePath: closePath,
  30004. offset: offset,
  30005. updatable: updatable,
  30006. sideOrientation: sideOrientation,
  30007. instance: instance
  30008. }, scene);
  30009. };
  30010. /**
  30011. * Creates a plane polygonal mesh. By default, this is a disc.
  30012. * Please consider using the same method from the MeshBuilder class instead.
  30013. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  30014. * 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.
  30015. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30016. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30017. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30018. */
  30019. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  30020. if (scene === void 0) { scene = null; }
  30021. var options = {
  30022. radius: radius,
  30023. tessellation: tessellation,
  30024. sideOrientation: sideOrientation,
  30025. updatable: updatable
  30026. };
  30027. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  30028. };
  30029. /**
  30030. * Creates a box mesh.
  30031. * Please consider using the same method from the MeshBuilder class instead.
  30032. * The parameter `size` sets the size (float) of each box side (default 1).
  30033. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30034. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30035. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30036. */
  30037. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  30038. if (scene === void 0) { scene = null; }
  30039. var options = {
  30040. size: size,
  30041. sideOrientation: sideOrientation,
  30042. updatable: updatable
  30043. };
  30044. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  30045. };
  30046. /**
  30047. * Creates a sphere mesh.
  30048. * Please consider using the same method from the MeshBuilder class instead.
  30049. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  30050. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  30051. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30052. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30053. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30054. */
  30055. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  30056. var options = {
  30057. segments: segments,
  30058. diameterX: diameter,
  30059. diameterY: diameter,
  30060. diameterZ: diameter,
  30061. sideOrientation: sideOrientation,
  30062. updatable: updatable
  30063. };
  30064. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  30065. };
  30066. /**
  30067. * Creates a cylinder or a cone mesh.
  30068. * Please consider using the same method from the MeshBuilder class instead.
  30069. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  30070. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  30071. * 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.
  30072. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  30073. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  30074. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30075. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30076. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30077. */
  30078. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  30079. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  30080. if (scene !== undefined) {
  30081. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  30082. updatable = scene;
  30083. }
  30084. scene = subdivisions;
  30085. subdivisions = 1;
  30086. }
  30087. var options = {
  30088. height: height,
  30089. diameterTop: diameterTop,
  30090. diameterBottom: diameterBottom,
  30091. tessellation: tessellation,
  30092. subdivisions: subdivisions,
  30093. sideOrientation: sideOrientation,
  30094. updatable: updatable
  30095. };
  30096. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  30097. };
  30098. // Torus (Code from SharpDX.org)
  30099. /**
  30100. * Creates a torus mesh.
  30101. * Please consider using the same method from the MeshBuilder class instead.
  30102. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  30103. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  30104. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  30105. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30106. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30107. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30108. */
  30109. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  30110. var options = {
  30111. diameter: diameter,
  30112. thickness: thickness,
  30113. tessellation: tessellation,
  30114. sideOrientation: sideOrientation,
  30115. updatable: updatable
  30116. };
  30117. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  30118. };
  30119. /**
  30120. * Creates a torus knot mesh.
  30121. * Please consider using the same method from the MeshBuilder class instead.
  30122. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  30123. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  30124. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  30125. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  30126. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30127. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30128. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30129. */
  30130. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  30131. var options = {
  30132. radius: radius,
  30133. tube: tube,
  30134. radialSegments: radialSegments,
  30135. tubularSegments: tubularSegments,
  30136. p: p,
  30137. q: q,
  30138. sideOrientation: sideOrientation,
  30139. updatable: updatable
  30140. };
  30141. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  30142. };
  30143. /**
  30144. * Creates a line mesh.
  30145. * Please consider using the same method from the MeshBuilder class instead.
  30146. * 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.
  30147. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30148. * The parameter `points` is an array successive Vector3.
  30149. * 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
  30150. * When updating an instance, remember that only point positions can change, not the number of points.
  30151. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30152. */
  30153. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  30154. if (scene === void 0) { scene = null; }
  30155. if (updatable === void 0) { updatable = false; }
  30156. if (instance === void 0) { instance = null; }
  30157. var options = {
  30158. points: points,
  30159. updatable: updatable,
  30160. instance: instance
  30161. };
  30162. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  30163. };
  30164. /**
  30165. * Creates a dashed line mesh.
  30166. * Please consider using the same method from the MeshBuilder class instead.
  30167. * 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.
  30168. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30169. * The parameter `points` is an array successive Vector3.
  30170. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  30171. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  30172. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  30173. * 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
  30174. * When updating an instance, remember that only point positions can change, not the number of points.
  30175. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30176. */
  30177. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  30178. if (scene === void 0) { scene = null; }
  30179. var options = {
  30180. points: points,
  30181. dashSize: dashSize,
  30182. gapSize: gapSize,
  30183. dashNb: dashNb,
  30184. updatable: updatable,
  30185. instance: instance
  30186. };
  30187. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  30188. };
  30189. /**
  30190. * Creates a polygon mesh.
  30191. * Please consider using the same method from the MeshBuilder class instead.
  30192. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  30193. * 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.
  30194. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30195. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30196. * Remember you can only change the shape positions, not their number when updating a polygon.
  30197. */
  30198. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  30199. var options = {
  30200. shape: shape,
  30201. holes: holes,
  30202. updatable: updatable,
  30203. sideOrientation: sideOrientation
  30204. };
  30205. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  30206. };
  30207. /**
  30208. * Creates an extruded polygon mesh, with depth in the Y direction.
  30209. * Please consider using the same method from the MeshBuilder class instead.
  30210. */
  30211. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  30212. var options = {
  30213. shape: shape,
  30214. holes: holes,
  30215. depth: depth,
  30216. updatable: updatable,
  30217. sideOrientation: sideOrientation
  30218. };
  30219. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  30220. };
  30221. /**
  30222. * Creates an extruded shape mesh.
  30223. * 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.
  30224. * Please consider using the same method from the MeshBuilder class instead.
  30225. *
  30226. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30227. * 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
  30228. * extruded along the Z axis.
  30229. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30230. * 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.
  30231. * The parameter `scale` (float, default 1) is the value to scale the shape.
  30232. * 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
  30233. * 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
  30234. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30235. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30236. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30237. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30238. */
  30239. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  30240. if (scene === void 0) { scene = null; }
  30241. var options = {
  30242. shape: shape,
  30243. path: path,
  30244. scale: scale,
  30245. rotation: rotation,
  30246. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30247. sideOrientation: sideOrientation,
  30248. instance: instance,
  30249. updatable: updatable
  30250. };
  30251. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  30252. };
  30253. /**
  30254. * Creates an custom extruded shape mesh.
  30255. * 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.
  30256. * Please consider using the same method from the MeshBuilder class instead.
  30257. *
  30258. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30259. * 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
  30260. * extruded along the Z axis.
  30261. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30262. * 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
  30263. * and the distance of this point from the begining of the path :
  30264. * ```javascript
  30265. * var rotationFunction = function(i, distance) {
  30266. * // do things
  30267. * return rotationValue; }
  30268. * ```
  30269. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  30270. * 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
  30271. * and the distance of this point from the begining of the path :
  30272. * ```javascript
  30273. * var scaleFunction = function(i, distance) {
  30274. * // do things
  30275. * return scaleValue;}
  30276. * ```
  30277. * It must returns a float value that will be the scale value applied to the shape on each path point.
  30278. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  30279. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  30280. * 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
  30281. * 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
  30282. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30283. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30284. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30285. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30286. */
  30287. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  30288. var options = {
  30289. shape: shape,
  30290. path: path,
  30291. scaleFunction: scaleFunction,
  30292. rotationFunction: rotationFunction,
  30293. ribbonCloseArray: ribbonCloseArray,
  30294. ribbonClosePath: ribbonClosePath,
  30295. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30296. sideOrientation: sideOrientation,
  30297. instance: instance,
  30298. updatable: updatable
  30299. };
  30300. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  30301. };
  30302. /**
  30303. * Creates lathe mesh.
  30304. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  30305. * Please consider using the same method from the MeshBuilder class instead.
  30306. * 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
  30307. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  30308. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  30309. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  30310. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30311. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30312. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30313. */
  30314. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  30315. var options = {
  30316. shape: shape,
  30317. radius: radius,
  30318. tessellation: tessellation,
  30319. sideOrientation: sideOrientation,
  30320. updatable: updatable
  30321. };
  30322. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  30323. };
  30324. /**
  30325. * Creates a plane mesh.
  30326. * Please consider using the same method from the MeshBuilder class instead.
  30327. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  30328. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30329. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30330. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30331. */
  30332. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  30333. var options = {
  30334. size: size,
  30335. width: size,
  30336. height: size,
  30337. sideOrientation: sideOrientation,
  30338. updatable: updatable
  30339. };
  30340. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  30341. };
  30342. /**
  30343. * Creates a ground mesh.
  30344. * Please consider using the same method from the MeshBuilder class instead.
  30345. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  30346. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  30347. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30348. */
  30349. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  30350. var options = {
  30351. width: width,
  30352. height: height,
  30353. subdivisions: subdivisions,
  30354. updatable: updatable
  30355. };
  30356. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  30357. };
  30358. /**
  30359. * Creates a tiled ground mesh.
  30360. * Please consider using the same method from the MeshBuilder class instead.
  30361. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  30362. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  30363. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  30364. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  30365. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  30366. * numbers of subdivisions on the ground width and height of each tile.
  30367. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30368. */
  30369. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  30370. var options = {
  30371. xmin: xmin,
  30372. zmin: zmin,
  30373. xmax: xmax,
  30374. zmax: zmax,
  30375. subdivisions: subdivisions,
  30376. precision: precision,
  30377. updatable: updatable
  30378. };
  30379. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  30380. };
  30381. /**
  30382. * Creates a ground mesh from a height map.
  30383. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  30384. * Please consider using the same method from the MeshBuilder class instead.
  30385. * The parameter `url` sets the URL of the height map image resource.
  30386. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  30387. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  30388. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  30389. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  30390. * 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).
  30391. * This function is passed the newly built mesh :
  30392. * ```javascript
  30393. * function(mesh) { // do things
  30394. * return; }
  30395. * ```
  30396. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30397. */
  30398. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  30399. var options = {
  30400. width: width,
  30401. height: height,
  30402. subdivisions: subdivisions,
  30403. minHeight: minHeight,
  30404. maxHeight: maxHeight,
  30405. updatable: updatable,
  30406. onReady: onReady
  30407. };
  30408. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  30409. };
  30410. /**
  30411. * Creates a tube mesh.
  30412. * 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.
  30413. * Please consider using the same method from the MeshBuilder class instead.
  30414. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  30415. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  30416. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  30417. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  30418. * 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.
  30419. * It must return a radius value (positive float) :
  30420. * ```javascript
  30421. * var radiusFunction = function(i, distance) {
  30422. * // do things
  30423. * return radius; }
  30424. * ```
  30425. * 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
  30426. * 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
  30427. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30428. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30429. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30430. */
  30431. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  30432. var options = {
  30433. path: path,
  30434. radius: radius,
  30435. tessellation: tessellation,
  30436. radiusFunction: radiusFunction,
  30437. arc: 1,
  30438. cap: cap,
  30439. updatable: updatable,
  30440. sideOrientation: sideOrientation,
  30441. instance: instance
  30442. };
  30443. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  30444. };
  30445. /**
  30446. * Creates a polyhedron mesh.
  30447. * Please consider using the same method from the MeshBuilder class instead.
  30448. * 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
  30449. * to choose the wanted type.
  30450. * The parameter `size` (positive float, default 1) sets the polygon size.
  30451. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  30452. * 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`.
  30453. * 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
  30454. * 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)`).
  30455. * 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
  30456. * 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.
  30457. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30458. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30459. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30460. */
  30461. Mesh.CreatePolyhedron = function (name, options, scene) {
  30462. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  30463. };
  30464. /**
  30465. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  30466. * Please consider using the same method from the MeshBuilder class instead.
  30467. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  30468. * 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`).
  30469. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  30470. * 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.
  30471. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30472. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30473. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30474. */
  30475. Mesh.CreateIcoSphere = function (name, options, scene) {
  30476. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  30477. };
  30478. /**
  30479. * Creates a decal mesh.
  30480. * Please consider using the same method from the MeshBuilder class instead.
  30481. * 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.
  30482. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  30483. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  30484. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  30485. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  30486. */
  30487. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  30488. var options = {
  30489. position: position,
  30490. normal: normal,
  30491. size: size,
  30492. angle: angle
  30493. };
  30494. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  30495. };
  30496. // Skeletons
  30497. /**
  30498. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30499. */
  30500. Mesh.prototype.setPositionsForCPUSkinning = function () {
  30501. if (!this._sourcePositions) {
  30502. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30503. if (!source) {
  30504. return this._sourcePositions;
  30505. }
  30506. this._sourcePositions = new Float32Array(source);
  30507. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30508. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  30509. }
  30510. }
  30511. return this._sourcePositions;
  30512. };
  30513. /**
  30514. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30515. */
  30516. Mesh.prototype.setNormalsForCPUSkinning = function () {
  30517. if (!this._sourceNormals) {
  30518. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30519. if (!source) {
  30520. return this._sourceNormals;
  30521. }
  30522. this._sourceNormals = new Float32Array(source);
  30523. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30524. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  30525. }
  30526. }
  30527. return this._sourceNormals;
  30528. };
  30529. /**
  30530. * Updates the vertex buffer by applying transformation from the bones.
  30531. * Returns the Mesh.
  30532. *
  30533. * @param {skeleton} skeleton to apply
  30534. */
  30535. Mesh.prototype.applySkeleton = function (skeleton) {
  30536. if (!this.geometry) {
  30537. return this;
  30538. }
  30539. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30540. return this;
  30541. }
  30542. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30543. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30544. return this;
  30545. }
  30546. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30547. return this;
  30548. }
  30549. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30550. return this;
  30551. }
  30552. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30553. return this;
  30554. }
  30555. if (!this._sourcePositions) {
  30556. var submeshes = this.subMeshes.slice();
  30557. this.setPositionsForCPUSkinning();
  30558. this.subMeshes = submeshes;
  30559. }
  30560. if (!this._sourceNormals) {
  30561. this.setNormalsForCPUSkinning();
  30562. }
  30563. // positionsData checks for not being Float32Array will only pass at most once
  30564. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30565. if (!positionsData) {
  30566. return this;
  30567. }
  30568. if (!(positionsData instanceof Float32Array)) {
  30569. positionsData = new Float32Array(positionsData);
  30570. }
  30571. // normalsData checks for not being Float32Array will only pass at most once
  30572. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30573. if (!normalsData) {
  30574. return this;
  30575. }
  30576. if (!(normalsData instanceof Float32Array)) {
  30577. normalsData = new Float32Array(normalsData);
  30578. }
  30579. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30580. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30581. if (!matricesWeightsData || !matricesIndicesData) {
  30582. return this;
  30583. }
  30584. var needExtras = this.numBoneInfluencers > 4;
  30585. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30586. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30587. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30588. var tempVector3 = BABYLON.Vector3.Zero();
  30589. var finalMatrix = new BABYLON.Matrix();
  30590. var tempMatrix = new BABYLON.Matrix();
  30591. var matWeightIdx = 0;
  30592. var inf;
  30593. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30594. var weight;
  30595. for (inf = 0; inf < 4; inf++) {
  30596. weight = matricesWeightsData[matWeightIdx + inf];
  30597. if (weight > 0) {
  30598. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30599. finalMatrix.addToSelf(tempMatrix);
  30600. }
  30601. else
  30602. break;
  30603. }
  30604. if (needExtras) {
  30605. for (inf = 0; inf < 4; inf++) {
  30606. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30607. if (weight > 0) {
  30608. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30609. finalMatrix.addToSelf(tempMatrix);
  30610. }
  30611. else
  30612. break;
  30613. }
  30614. }
  30615. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30616. tempVector3.toArray(positionsData, index);
  30617. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30618. tempVector3.toArray(normalsData, index);
  30619. finalMatrix.reset();
  30620. }
  30621. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30622. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30623. return this;
  30624. };
  30625. // Tools
  30626. /**
  30627. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30628. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30629. */
  30630. Mesh.MinMax = function (meshes) {
  30631. var minVector = null;
  30632. var maxVector = null;
  30633. meshes.forEach(function (mesh, index, array) {
  30634. var boundingInfo = mesh.getBoundingInfo();
  30635. var boundingBox = boundingInfo.boundingBox;
  30636. if (!minVector || !maxVector) {
  30637. minVector = boundingBox.minimumWorld;
  30638. maxVector = boundingBox.maximumWorld;
  30639. }
  30640. else {
  30641. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30642. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30643. }
  30644. });
  30645. if (!minVector || !maxVector) {
  30646. return {
  30647. min: BABYLON.Vector3.Zero(),
  30648. max: BABYLON.Vector3.Zero()
  30649. };
  30650. }
  30651. return {
  30652. min: minVector,
  30653. max: maxVector
  30654. };
  30655. };
  30656. /**
  30657. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30658. */
  30659. Mesh.Center = function (meshesOrMinMaxVector) {
  30660. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30661. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30662. };
  30663. /**
  30664. * Merge the array of meshes into a single mesh for performance reasons.
  30665. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30666. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30667. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30668. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30669. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30670. */
  30671. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30672. if (disposeSource === void 0) { disposeSource = true; }
  30673. var index;
  30674. if (!allow32BitsIndices) {
  30675. var totalVertices = 0;
  30676. // Counting vertices
  30677. for (index = 0; index < meshes.length; index++) {
  30678. if (meshes[index]) {
  30679. totalVertices += meshes[index].getTotalVertices();
  30680. if (totalVertices > 65536) {
  30681. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30682. return null;
  30683. }
  30684. }
  30685. }
  30686. }
  30687. // Merge
  30688. var vertexData = null;
  30689. var otherVertexData;
  30690. var indiceArray = new Array();
  30691. var source = null;
  30692. for (index = 0; index < meshes.length; index++) {
  30693. if (meshes[index]) {
  30694. meshes[index].computeWorldMatrix(true);
  30695. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30696. otherVertexData.transform(meshes[index].getWorldMatrix());
  30697. if (vertexData) {
  30698. vertexData.merge(otherVertexData);
  30699. }
  30700. else {
  30701. vertexData = otherVertexData;
  30702. source = meshes[index];
  30703. }
  30704. if (subdivideWithSubMeshes) {
  30705. indiceArray.push(meshes[index].getTotalIndices());
  30706. }
  30707. }
  30708. }
  30709. source = source;
  30710. if (!meshSubclass) {
  30711. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30712. }
  30713. vertexData.applyToMesh(meshSubclass);
  30714. // Setting properties
  30715. meshSubclass.material = source.material;
  30716. meshSubclass.checkCollisions = source.checkCollisions;
  30717. // Cleaning
  30718. if (disposeSource) {
  30719. for (index = 0; index < meshes.length; index++) {
  30720. if (meshes[index]) {
  30721. meshes[index].dispose();
  30722. }
  30723. }
  30724. }
  30725. // Subdivide
  30726. if (subdivideWithSubMeshes) {
  30727. //-- Suppresions du submesh global
  30728. meshSubclass.releaseSubMeshes();
  30729. index = 0;
  30730. var offset = 0;
  30731. //-- aplique la subdivision en fonction du tableau d'indices
  30732. while (index < indiceArray.length) {
  30733. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30734. offset += indiceArray[index];
  30735. index++;
  30736. }
  30737. }
  30738. return meshSubclass;
  30739. };
  30740. // Consts
  30741. Mesh._FRONTSIDE = 0;
  30742. Mesh._BACKSIDE = 1;
  30743. Mesh._DOUBLESIDE = 2;
  30744. Mesh._DEFAULTSIDE = 0;
  30745. Mesh._NO_CAP = 0;
  30746. Mesh._CAP_START = 1;
  30747. Mesh._CAP_END = 2;
  30748. Mesh._CAP_ALL = 3;
  30749. return Mesh;
  30750. }(BABYLON.AbstractMesh));
  30751. BABYLON.Mesh = Mesh;
  30752. })(BABYLON || (BABYLON = {}));
  30753. //# sourceMappingURL=babylon.mesh.js.map
  30754. "use strict";
  30755. var BABYLON;
  30756. (function (BABYLON) {
  30757. var BaseSubMesh = /** @class */ (function () {
  30758. function BaseSubMesh() {
  30759. }
  30760. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30761. get: function () {
  30762. return this._materialEffect;
  30763. },
  30764. enumerable: true,
  30765. configurable: true
  30766. });
  30767. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30768. if (defines === void 0) { defines = null; }
  30769. if (this._materialEffect === effect) {
  30770. if (!effect) {
  30771. this._materialDefines = null;
  30772. }
  30773. return;
  30774. }
  30775. this._materialDefines = defines;
  30776. this._materialEffect = effect;
  30777. };
  30778. return BaseSubMesh;
  30779. }());
  30780. BABYLON.BaseSubMesh = BaseSubMesh;
  30781. var SubMesh = /** @class */ (function (_super) {
  30782. __extends(SubMesh, _super);
  30783. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30784. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30785. var _this = _super.call(this) || this;
  30786. _this.materialIndex = materialIndex;
  30787. _this.verticesStart = verticesStart;
  30788. _this.verticesCount = verticesCount;
  30789. _this.indexStart = indexStart;
  30790. _this.indexCount = indexCount;
  30791. _this._renderId = 0;
  30792. _this._mesh = mesh;
  30793. _this._renderingMesh = renderingMesh || mesh;
  30794. mesh.subMeshes.push(_this);
  30795. _this._trianglePlanes = [];
  30796. _this._id = mesh.subMeshes.length - 1;
  30797. if (createBoundingBox) {
  30798. _this.refreshBoundingInfo();
  30799. mesh.computeWorldMatrix(true);
  30800. }
  30801. return _this;
  30802. }
  30803. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30804. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30805. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30806. };
  30807. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30808. get: function () {
  30809. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30810. },
  30811. enumerable: true,
  30812. configurable: true
  30813. });
  30814. /**
  30815. * Returns the submesh BoudingInfo object.
  30816. */
  30817. SubMesh.prototype.getBoundingInfo = function () {
  30818. if (this.IsGlobal) {
  30819. return this._mesh.getBoundingInfo();
  30820. }
  30821. return this._boundingInfo;
  30822. };
  30823. /**
  30824. * Sets the submesh BoundingInfo.
  30825. * Return the SubMesh.
  30826. */
  30827. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30828. this._boundingInfo = boundingInfo;
  30829. return this;
  30830. };
  30831. /**
  30832. * Returns the mesh of the current submesh.
  30833. */
  30834. SubMesh.prototype.getMesh = function () {
  30835. return this._mesh;
  30836. };
  30837. /**
  30838. * Returns the rendering mesh of the submesh.
  30839. */
  30840. SubMesh.prototype.getRenderingMesh = function () {
  30841. return this._renderingMesh;
  30842. };
  30843. /**
  30844. * Returns the submesh material.
  30845. */
  30846. SubMesh.prototype.getMaterial = function () {
  30847. var rootMaterial = this._renderingMesh.material;
  30848. if (rootMaterial === null || rootMaterial === undefined) {
  30849. return this._mesh.getScene().defaultMaterial;
  30850. }
  30851. else if (rootMaterial.getSubMaterial) {
  30852. var multiMaterial = rootMaterial;
  30853. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30854. if (this._currentMaterial !== effectiveMaterial) {
  30855. this._currentMaterial = effectiveMaterial;
  30856. this._materialDefines = null;
  30857. }
  30858. return effectiveMaterial;
  30859. }
  30860. return rootMaterial;
  30861. };
  30862. // Methods
  30863. /**
  30864. * Sets a new updated BoundingInfo object to the submesh.
  30865. * Returns the SubMesh.
  30866. */
  30867. SubMesh.prototype.refreshBoundingInfo = function () {
  30868. this._lastColliderWorldVertices = null;
  30869. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30870. return this;
  30871. }
  30872. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30873. if (!data) {
  30874. this._boundingInfo = this._mesh.getBoundingInfo();
  30875. return this;
  30876. }
  30877. var indices = this._renderingMesh.getIndices();
  30878. var extend;
  30879. //is this the only submesh?
  30880. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30881. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30882. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30883. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30884. }
  30885. else {
  30886. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30887. }
  30888. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30889. return this;
  30890. };
  30891. SubMesh.prototype._checkCollision = function (collider) {
  30892. var boundingInfo = this.getBoundingInfo();
  30893. return boundingInfo._checkCollision(collider);
  30894. };
  30895. /**
  30896. * Updates the submesh BoundingInfo.
  30897. * Returns the Submesh.
  30898. */
  30899. SubMesh.prototype.updateBoundingInfo = function (world) {
  30900. var boundingInfo = this.getBoundingInfo();
  30901. if (!boundingInfo) {
  30902. this.refreshBoundingInfo();
  30903. boundingInfo = this.getBoundingInfo();
  30904. }
  30905. boundingInfo.update(world);
  30906. return this;
  30907. };
  30908. /**
  30909. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30910. * Boolean returned.
  30911. */
  30912. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30913. var boundingInfo = this.getBoundingInfo();
  30914. if (!boundingInfo) {
  30915. return false;
  30916. }
  30917. return boundingInfo.isInFrustum(frustumPlanes);
  30918. };
  30919. /**
  30920. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30921. * Boolean returned.
  30922. */
  30923. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30924. var boundingInfo = this.getBoundingInfo();
  30925. if (!boundingInfo) {
  30926. return false;
  30927. }
  30928. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30929. };
  30930. /**
  30931. * Renders the submesh.
  30932. * Returns it.
  30933. */
  30934. SubMesh.prototype.render = function (enableAlphaMode) {
  30935. this._renderingMesh.render(this, enableAlphaMode);
  30936. return this;
  30937. };
  30938. /**
  30939. * Returns a new Index Buffer.
  30940. * Type returned : WebGLBuffer.
  30941. */
  30942. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30943. if (!this._linesIndexBuffer) {
  30944. var linesIndices = [];
  30945. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30946. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30947. }
  30948. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30949. this.linesIndexCount = linesIndices.length;
  30950. }
  30951. return this._linesIndexBuffer;
  30952. };
  30953. /**
  30954. * True is the passed Ray intersects the submesh bounding box.
  30955. * Boolean returned.
  30956. */
  30957. SubMesh.prototype.canIntersects = function (ray) {
  30958. var boundingInfo = this.getBoundingInfo();
  30959. if (!boundingInfo) {
  30960. return false;
  30961. }
  30962. return ray.intersectsBox(boundingInfo.boundingBox);
  30963. };
  30964. /**
  30965. * Returns an object IntersectionInfo.
  30966. */
  30967. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30968. var intersectInfo = null;
  30969. var material = this.getMaterial();
  30970. if (!material) {
  30971. return null;
  30972. }
  30973. switch (material.fillMode) {
  30974. case BABYLON.Material.PointListDrawMode:
  30975. case BABYLON.Material.LineListDrawMode:
  30976. case BABYLON.Material.LineLoopDrawMode:
  30977. case BABYLON.Material.LineStripDrawMode:
  30978. case BABYLON.Material.TriangleFanDrawMode:
  30979. case BABYLON.Material.TriangleStripDrawMode:
  30980. return null;
  30981. }
  30982. // LineMesh first as it's also a Mesh...
  30983. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  30984. var lineMesh = this._mesh;
  30985. // Line test
  30986. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  30987. var p0 = positions[indices[index]];
  30988. var p1 = positions[indices[index + 1]];
  30989. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  30990. if (length < 0) {
  30991. continue;
  30992. }
  30993. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  30994. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  30995. if (fastCheck) {
  30996. break;
  30997. }
  30998. }
  30999. }
  31000. }
  31001. else {
  31002. // Triangles test
  31003. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  31004. var p0 = positions[indices[index]];
  31005. var p1 = positions[indices[index + 1]];
  31006. var p2 = positions[indices[index + 2]];
  31007. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  31008. if (currentIntersectInfo) {
  31009. if (currentIntersectInfo.distance < 0) {
  31010. continue;
  31011. }
  31012. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  31013. intersectInfo = currentIntersectInfo;
  31014. intersectInfo.faceId = index / 3;
  31015. if (fastCheck) {
  31016. break;
  31017. }
  31018. }
  31019. }
  31020. }
  31021. }
  31022. return intersectInfo;
  31023. };
  31024. SubMesh.prototype._rebuild = function () {
  31025. if (this._linesIndexBuffer) {
  31026. this._linesIndexBuffer = null;
  31027. }
  31028. };
  31029. // Clone
  31030. /**
  31031. * Creates a new Submesh from the passed Mesh.
  31032. */
  31033. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  31034. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  31035. if (!this.IsGlobal) {
  31036. var boundingInfo = this.getBoundingInfo();
  31037. if (!boundingInfo) {
  31038. return result;
  31039. }
  31040. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  31041. }
  31042. return result;
  31043. };
  31044. // Dispose
  31045. /**
  31046. * Disposes the Submesh.
  31047. * Returns nothing.
  31048. */
  31049. SubMesh.prototype.dispose = function () {
  31050. if (this._linesIndexBuffer) {
  31051. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  31052. this._linesIndexBuffer = null;
  31053. }
  31054. // Remove from mesh
  31055. var index = this._mesh.subMeshes.indexOf(this);
  31056. this._mesh.subMeshes.splice(index, 1);
  31057. };
  31058. // Statics
  31059. /**
  31060. * Creates a new Submesh from the passed parameters :
  31061. * - materialIndex (integer) : the index of the main mesh material.
  31062. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  31063. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  31064. * - mesh (Mesh) : the main mesh to create the submesh from.
  31065. * - renderingMesh (optional Mesh) : rendering mesh.
  31066. */
  31067. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  31068. var minVertexIndex = Number.MAX_VALUE;
  31069. var maxVertexIndex = -Number.MAX_VALUE;
  31070. renderingMesh = (renderingMesh || mesh);
  31071. var indices = renderingMesh.getIndices();
  31072. for (var index = startIndex; index < startIndex + indexCount; index++) {
  31073. var vertexIndex = indices[index];
  31074. if (vertexIndex < minVertexIndex)
  31075. minVertexIndex = vertexIndex;
  31076. if (vertexIndex > maxVertexIndex)
  31077. maxVertexIndex = vertexIndex;
  31078. }
  31079. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  31080. };
  31081. return SubMesh;
  31082. }(BaseSubMesh));
  31083. BABYLON.SubMesh = SubMesh;
  31084. })(BABYLON || (BABYLON = {}));
  31085. //# sourceMappingURL=babylon.subMesh.js.map
  31086. "use strict";
  31087. var __assign = (this && this.__assign) || Object.assign || function(t) {
  31088. for (var s, i = 1, n = arguments.length; i < n; i++) {
  31089. s = arguments[i];
  31090. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  31091. t[p] = s[p];
  31092. }
  31093. return t;
  31094. };
  31095. var BABYLON;
  31096. (function (BABYLON) {
  31097. /**
  31098. * Manages the defines for the Material.
  31099. */
  31100. var MaterialDefines = /** @class */ (function () {
  31101. function MaterialDefines() {
  31102. this._isDirty = true;
  31103. this._areLightsDirty = true;
  31104. this._areAttributesDirty = true;
  31105. this._areTexturesDirty = true;
  31106. this._areFresnelDirty = true;
  31107. this._areMiscDirty = true;
  31108. this._areImageProcessingDirty = true;
  31109. this._normals = false;
  31110. this._uvs = false;
  31111. this._needNormals = false;
  31112. this._needUVs = false;
  31113. }
  31114. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  31115. /**
  31116. * Specifies if the material needs to be re-calculated.
  31117. */
  31118. get: function () {
  31119. return this._isDirty;
  31120. },
  31121. enumerable: true,
  31122. configurable: true
  31123. });
  31124. /**
  31125. * Marks the material to indicate that it has been re-calculated.
  31126. */
  31127. MaterialDefines.prototype.markAsProcessed = function () {
  31128. this._isDirty = false;
  31129. this._areAttributesDirty = false;
  31130. this._areTexturesDirty = false;
  31131. this._areFresnelDirty = false;
  31132. this._areLightsDirty = false;
  31133. this._areMiscDirty = false;
  31134. this._areImageProcessingDirty = false;
  31135. };
  31136. /**
  31137. * Marks the material to indicate that it needs to be re-calculated.
  31138. */
  31139. MaterialDefines.prototype.markAsUnprocessed = function () {
  31140. this._isDirty = true;
  31141. };
  31142. /**
  31143. * Marks the material to indicate all of its defines need to be re-calculated.
  31144. */
  31145. MaterialDefines.prototype.markAllAsDirty = function () {
  31146. this._areTexturesDirty = true;
  31147. this._areAttributesDirty = true;
  31148. this._areLightsDirty = true;
  31149. this._areFresnelDirty = true;
  31150. this._areMiscDirty = true;
  31151. this._areImageProcessingDirty = true;
  31152. this._isDirty = true;
  31153. };
  31154. /**
  31155. * Marks the material to indicate that image processing needs to be re-calculated.
  31156. */
  31157. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  31158. this._areImageProcessingDirty = true;
  31159. this._isDirty = true;
  31160. };
  31161. /**
  31162. * Marks the material to indicate the lights need to be re-calculated.
  31163. */
  31164. MaterialDefines.prototype.markAsLightDirty = function () {
  31165. this._areLightsDirty = true;
  31166. this._isDirty = true;
  31167. };
  31168. /**
  31169. * Marks the attribute state as changed.
  31170. */
  31171. MaterialDefines.prototype.markAsAttributesDirty = function () {
  31172. this._areAttributesDirty = true;
  31173. this._isDirty = true;
  31174. };
  31175. /**
  31176. * Marks the texture state as changed.
  31177. */
  31178. MaterialDefines.prototype.markAsTexturesDirty = function () {
  31179. this._areTexturesDirty = true;
  31180. this._isDirty = true;
  31181. };
  31182. /**
  31183. * Marks the fresnel state as changed.
  31184. */
  31185. MaterialDefines.prototype.markAsFresnelDirty = function () {
  31186. this._areFresnelDirty = true;
  31187. this._isDirty = true;
  31188. };
  31189. /**
  31190. * Marks the misc state as changed.
  31191. */
  31192. MaterialDefines.prototype.markAsMiscDirty = function () {
  31193. this._areMiscDirty = true;
  31194. this._isDirty = true;
  31195. };
  31196. /**
  31197. * Rebuilds the material defines.
  31198. */
  31199. MaterialDefines.prototype.rebuild = function () {
  31200. if (this._keys) {
  31201. delete this._keys;
  31202. }
  31203. this._keys = [];
  31204. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  31205. var key = _a[_i];
  31206. if (key[0] === "_") {
  31207. continue;
  31208. }
  31209. this._keys.push(key);
  31210. }
  31211. };
  31212. /**
  31213. * Specifies if two material defines are equal.
  31214. * @param other - A material define instance to compare to.
  31215. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  31216. */
  31217. MaterialDefines.prototype.isEqual = function (other) {
  31218. if (this._keys.length !== other._keys.length) {
  31219. return false;
  31220. }
  31221. for (var index = 0; index < this._keys.length; index++) {
  31222. var prop = this._keys[index];
  31223. if (this[prop] !== other[prop]) {
  31224. return false;
  31225. }
  31226. }
  31227. return true;
  31228. };
  31229. /**
  31230. * Clones this instance's defines to another instance.
  31231. * @param other - material defines to clone values to.
  31232. */
  31233. MaterialDefines.prototype.cloneTo = function (other) {
  31234. if (this._keys.length !== other._keys.length) {
  31235. other._keys = this._keys.slice(0);
  31236. }
  31237. for (var index = 0; index < this._keys.length; index++) {
  31238. var prop = this._keys[index];
  31239. other[prop] = this[prop];
  31240. }
  31241. };
  31242. /**
  31243. * Resets the material define values.
  31244. */
  31245. MaterialDefines.prototype.reset = function () {
  31246. for (var index = 0; index < this._keys.length; index++) {
  31247. var prop = this._keys[index];
  31248. var type = typeof this[prop];
  31249. switch (type) {
  31250. case "number":
  31251. this[prop] = 0;
  31252. break;
  31253. case "string":
  31254. this[prop] = "";
  31255. break;
  31256. default:
  31257. this[prop] = false;
  31258. break;
  31259. }
  31260. }
  31261. };
  31262. /**
  31263. * Converts the material define values to a string.
  31264. * @returns - String of material define information.
  31265. */
  31266. MaterialDefines.prototype.toString = function () {
  31267. var result = "";
  31268. for (var index = 0; index < this._keys.length; index++) {
  31269. var prop = this._keys[index];
  31270. var value = this[prop];
  31271. var type = typeof value;
  31272. switch (type) {
  31273. case "number":
  31274. case "string":
  31275. result += "#define " + prop + " " + value + "\n";
  31276. break;
  31277. default:
  31278. if (value) {
  31279. result += "#define " + prop + "\n";
  31280. }
  31281. break;
  31282. }
  31283. }
  31284. return result;
  31285. };
  31286. return MaterialDefines;
  31287. }());
  31288. BABYLON.MaterialDefines = MaterialDefines;
  31289. /**
  31290. * This offers the main features of a material in BJS.
  31291. */
  31292. var Material = /** @class */ (function () {
  31293. /**
  31294. * Creates a material instance.
  31295. * @param name - The name of the material.
  31296. * @param scene - The BJS scene to reference.
  31297. * @param doNotAdd - Specifies if the material should be added to the scene.
  31298. */
  31299. function Material(name, scene, doNotAdd) {
  31300. /**
  31301. * Specifies if the ready state should be checked on each call.
  31302. */
  31303. this.checkReadyOnEveryCall = false;
  31304. /**
  31305. * Specifies if the ready state should be checked once.
  31306. */
  31307. this.checkReadyOnlyOnce = false;
  31308. /**
  31309. * The state of the material.
  31310. */
  31311. this.state = "";
  31312. /**
  31313. * The alpha value of the material.
  31314. */
  31315. this._alpha = 1.0;
  31316. /**
  31317. * Specifies if back face culling is enabled.
  31318. */
  31319. this._backFaceCulling = true;
  31320. /**
  31321. * Specifies if the material should be serialized.
  31322. */
  31323. this.doNotSerialize = false;
  31324. /**
  31325. * Specifies if the effect should be stored on sub meshes.
  31326. */
  31327. this.storeEffectOnSubMeshes = false;
  31328. /**
  31329. * An event triggered when the material is disposed.
  31330. * @type {BABYLON.Observable}
  31331. */
  31332. this.onDisposeObservable = new BABYLON.Observable();
  31333. /**
  31334. * An event triggered when the material is bound.
  31335. * @type {BABYLON.Observable}
  31336. */
  31337. this.onBindObservable = new BABYLON.Observable();
  31338. /**
  31339. * An event triggered when the material is unbound.
  31340. * @type {BABYLON.Observable}
  31341. */
  31342. this.onUnBindObservable = new BABYLON.Observable();
  31343. /**
  31344. * Stores the value of the alpha mode.
  31345. */
  31346. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  31347. /**
  31348. * Stores the state of the need depth pre-pass value.
  31349. */
  31350. this._needDepthPrePass = false;
  31351. /**
  31352. * Specifies if depth writing should be disabled.
  31353. */
  31354. this.disableDepthWrite = false;
  31355. /**
  31356. * Specifies if depth writing should be forced.
  31357. */
  31358. this.forceDepthWrite = false;
  31359. /**
  31360. * Specifies if there should be a separate pass for culling.
  31361. */
  31362. this.separateCullingPass = false;
  31363. /**
  31364. * Stores the state specifing if fog should be enabled.
  31365. */
  31366. this._fogEnabled = true;
  31367. /**
  31368. * Stores the size of points.
  31369. */
  31370. this.pointSize = 1.0;
  31371. /**
  31372. * Stores the z offset value.
  31373. */
  31374. this.zOffset = 0;
  31375. /**
  31376. * Specifies if the material was previously ready.
  31377. */
  31378. this._wasPreviouslyReady = false;
  31379. /**
  31380. * Stores the fill mode state.
  31381. */
  31382. this._fillMode = Material.TriangleFillMode;
  31383. this.name = name;
  31384. this.id = name || BABYLON.Tools.RandomId();
  31385. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31386. if (this._scene.useRightHandedSystem) {
  31387. this.sideOrientation = Material.ClockWiseSideOrientation;
  31388. }
  31389. else {
  31390. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  31391. }
  31392. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  31393. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  31394. if (!doNotAdd) {
  31395. this._scene.materials.push(this);
  31396. }
  31397. }
  31398. Object.defineProperty(Material, "TriangleFillMode", {
  31399. /**
  31400. * Returns the triangle fill mode.
  31401. */
  31402. get: function () {
  31403. return Material._TriangleFillMode;
  31404. },
  31405. enumerable: true,
  31406. configurable: true
  31407. });
  31408. Object.defineProperty(Material, "WireFrameFillMode", {
  31409. /**
  31410. * Returns the wireframe mode.
  31411. */
  31412. get: function () {
  31413. return Material._WireFrameFillMode;
  31414. },
  31415. enumerable: true,
  31416. configurable: true
  31417. });
  31418. Object.defineProperty(Material, "PointFillMode", {
  31419. /**
  31420. * Returns the point fill mode.
  31421. */
  31422. get: function () {
  31423. return Material._PointFillMode;
  31424. },
  31425. enumerable: true,
  31426. configurable: true
  31427. });
  31428. Object.defineProperty(Material, "PointListDrawMode", {
  31429. /**
  31430. * Returns the point list draw mode.
  31431. */
  31432. get: function () {
  31433. return Material._PointListDrawMode;
  31434. },
  31435. enumerable: true,
  31436. configurable: true
  31437. });
  31438. Object.defineProperty(Material, "LineListDrawMode", {
  31439. /**
  31440. * Returns the line list draw mode.
  31441. */
  31442. get: function () {
  31443. return Material._LineListDrawMode;
  31444. },
  31445. enumerable: true,
  31446. configurable: true
  31447. });
  31448. Object.defineProperty(Material, "LineLoopDrawMode", {
  31449. /**
  31450. * Returns the line loop draw mode.
  31451. */
  31452. get: function () {
  31453. return Material._LineLoopDrawMode;
  31454. },
  31455. enumerable: true,
  31456. configurable: true
  31457. });
  31458. Object.defineProperty(Material, "LineStripDrawMode", {
  31459. /**
  31460. * Returns the line strip draw mode.
  31461. */
  31462. get: function () {
  31463. return Material._LineStripDrawMode;
  31464. },
  31465. enumerable: true,
  31466. configurable: true
  31467. });
  31468. Object.defineProperty(Material, "TriangleStripDrawMode", {
  31469. /**
  31470. * Returns the triangle strip draw mode.
  31471. */
  31472. get: function () {
  31473. return Material._TriangleStripDrawMode;
  31474. },
  31475. enumerable: true,
  31476. configurable: true
  31477. });
  31478. Object.defineProperty(Material, "TriangleFanDrawMode", {
  31479. /**
  31480. * Returns the triangle fan draw mode.
  31481. */
  31482. get: function () {
  31483. return Material._TriangleFanDrawMode;
  31484. },
  31485. enumerable: true,
  31486. configurable: true
  31487. });
  31488. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  31489. /**
  31490. * Returns the clock-wise side orientation.
  31491. */
  31492. get: function () {
  31493. return Material._ClockWiseSideOrientation;
  31494. },
  31495. enumerable: true,
  31496. configurable: true
  31497. });
  31498. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  31499. /**
  31500. * Returns the counter clock-wise side orientation.
  31501. */
  31502. get: function () {
  31503. return Material._CounterClockWiseSideOrientation;
  31504. },
  31505. enumerable: true,
  31506. configurable: true
  31507. });
  31508. Object.defineProperty(Material, "TextureDirtyFlag", {
  31509. /**
  31510. * Returns the dirty texture flag value.
  31511. */
  31512. get: function () {
  31513. return Material._TextureDirtyFlag;
  31514. },
  31515. enumerable: true,
  31516. configurable: true
  31517. });
  31518. Object.defineProperty(Material, "LightDirtyFlag", {
  31519. /**
  31520. * Returns the dirty light flag value.
  31521. */
  31522. get: function () {
  31523. return Material._LightDirtyFlag;
  31524. },
  31525. enumerable: true,
  31526. configurable: true
  31527. });
  31528. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31529. /**
  31530. * Returns the dirty fresnel flag value.
  31531. */
  31532. get: function () {
  31533. return Material._FresnelDirtyFlag;
  31534. },
  31535. enumerable: true,
  31536. configurable: true
  31537. });
  31538. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31539. /**
  31540. * Returns the dirty attributes flag value.
  31541. */
  31542. get: function () {
  31543. return Material._AttributesDirtyFlag;
  31544. },
  31545. enumerable: true,
  31546. configurable: true
  31547. });
  31548. Object.defineProperty(Material, "MiscDirtyFlag", {
  31549. /**
  31550. * Returns the dirty misc flag value.
  31551. */
  31552. get: function () {
  31553. return Material._MiscDirtyFlag;
  31554. },
  31555. enumerable: true,
  31556. configurable: true
  31557. });
  31558. Object.defineProperty(Material.prototype, "alpha", {
  31559. /**
  31560. * Gets the alpha value of the material.
  31561. */
  31562. get: function () {
  31563. return this._alpha;
  31564. },
  31565. /**
  31566. * Sets the alpha value of the material.
  31567. */
  31568. set: function (value) {
  31569. if (this._alpha === value) {
  31570. return;
  31571. }
  31572. this._alpha = value;
  31573. this.markAsDirty(Material.MiscDirtyFlag);
  31574. },
  31575. enumerable: true,
  31576. configurable: true
  31577. });
  31578. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31579. /**
  31580. * Gets the back-face culling state.
  31581. */
  31582. get: function () {
  31583. return this._backFaceCulling;
  31584. },
  31585. /**
  31586. * Sets the back-face culling state.
  31587. */
  31588. set: function (value) {
  31589. if (this._backFaceCulling === value) {
  31590. return;
  31591. }
  31592. this._backFaceCulling = value;
  31593. this.markAsDirty(Material.TextureDirtyFlag);
  31594. },
  31595. enumerable: true,
  31596. configurable: true
  31597. });
  31598. Object.defineProperty(Material.prototype, "onDispose", {
  31599. /**
  31600. * Called during a dispose event.
  31601. */
  31602. set: function (callback) {
  31603. if (this._onDisposeObserver) {
  31604. this.onDisposeObservable.remove(this._onDisposeObserver);
  31605. }
  31606. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31607. },
  31608. enumerable: true,
  31609. configurable: true
  31610. });
  31611. Object.defineProperty(Material.prototype, "onBind", {
  31612. /**
  31613. * Called during a bind event.
  31614. */
  31615. set: function (callback) {
  31616. if (this._onBindObserver) {
  31617. this.onBindObservable.remove(this._onBindObserver);
  31618. }
  31619. this._onBindObserver = this.onBindObservable.add(callback);
  31620. },
  31621. enumerable: true,
  31622. configurable: true
  31623. });
  31624. Object.defineProperty(Material.prototype, "alphaMode", {
  31625. /**
  31626. * Gets the value of the alpha mode.
  31627. */
  31628. get: function () {
  31629. return this._alphaMode;
  31630. },
  31631. /**
  31632. * Sets the value of the alpha mode.
  31633. */
  31634. set: function (value) {
  31635. if (this._alphaMode === value) {
  31636. return;
  31637. }
  31638. this._alphaMode = value;
  31639. this.markAsDirty(Material.TextureDirtyFlag);
  31640. },
  31641. enumerable: true,
  31642. configurable: true
  31643. });
  31644. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31645. /**
  31646. * Gets the depth pre-pass value.
  31647. */
  31648. get: function () {
  31649. return this._needDepthPrePass;
  31650. },
  31651. /**
  31652. * Sets the need depth pre-pass value.
  31653. */
  31654. set: function (value) {
  31655. if (this._needDepthPrePass === value) {
  31656. return;
  31657. }
  31658. this._needDepthPrePass = value;
  31659. if (this._needDepthPrePass) {
  31660. this.checkReadyOnEveryCall = true;
  31661. }
  31662. },
  31663. enumerable: true,
  31664. configurable: true
  31665. });
  31666. Object.defineProperty(Material.prototype, "fogEnabled", {
  31667. /**
  31668. * Gets the value of the fog enabled state.
  31669. */
  31670. get: function () {
  31671. return this._fogEnabled;
  31672. },
  31673. /**
  31674. * Sets the state for enabling fog.
  31675. */
  31676. set: function (value) {
  31677. if (this._fogEnabled === value) {
  31678. return;
  31679. }
  31680. this._fogEnabled = value;
  31681. this.markAsDirty(Material.MiscDirtyFlag);
  31682. },
  31683. enumerable: true,
  31684. configurable: true
  31685. });
  31686. Object.defineProperty(Material.prototype, "wireframe", {
  31687. /**
  31688. * Gets a value specifying if wireframe mode is enabled.
  31689. */
  31690. get: function () {
  31691. switch (this._fillMode) {
  31692. case Material.WireFrameFillMode:
  31693. case Material.LineListDrawMode:
  31694. case Material.LineLoopDrawMode:
  31695. case Material.LineStripDrawMode:
  31696. return true;
  31697. }
  31698. return this._scene.forceWireframe;
  31699. },
  31700. /**
  31701. * Sets the state of wireframe mode.
  31702. */
  31703. set: function (value) {
  31704. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31705. },
  31706. enumerable: true,
  31707. configurable: true
  31708. });
  31709. Object.defineProperty(Material.prototype, "pointsCloud", {
  31710. /**
  31711. * Gets the value specifying if point clouds are enabled.
  31712. */
  31713. get: function () {
  31714. switch (this._fillMode) {
  31715. case Material.PointFillMode:
  31716. case Material.PointListDrawMode:
  31717. return true;
  31718. }
  31719. return this._scene.forcePointsCloud;
  31720. },
  31721. /**
  31722. * Sets the state of point cloud mode.
  31723. */
  31724. set: function (value) {
  31725. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31726. },
  31727. enumerable: true,
  31728. configurable: true
  31729. });
  31730. Object.defineProperty(Material.prototype, "fillMode", {
  31731. /**
  31732. * Gets the material fill mode.
  31733. */
  31734. get: function () {
  31735. return this._fillMode;
  31736. },
  31737. /**
  31738. * Sets the material fill mode.
  31739. */
  31740. set: function (value) {
  31741. if (this._fillMode === value) {
  31742. return;
  31743. }
  31744. this._fillMode = value;
  31745. this.markAsDirty(Material.MiscDirtyFlag);
  31746. },
  31747. enumerable: true,
  31748. configurable: true
  31749. });
  31750. /**
  31751. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31752. * subclasses should override adding information pertainent to themselves.
  31753. * @returns - String with material information.
  31754. */
  31755. Material.prototype.toString = function (fullDetails) {
  31756. var ret = "Name: " + this.name;
  31757. if (fullDetails) {
  31758. }
  31759. return ret;
  31760. };
  31761. /**
  31762. * Gets the class name of the material.
  31763. * @returns - String with the class name of the material.
  31764. */
  31765. Material.prototype.getClassName = function () {
  31766. return "Material";
  31767. };
  31768. Object.defineProperty(Material.prototype, "isFrozen", {
  31769. /**
  31770. * Specifies if updates for the material been locked.
  31771. */
  31772. get: function () {
  31773. return this.checkReadyOnlyOnce;
  31774. },
  31775. enumerable: true,
  31776. configurable: true
  31777. });
  31778. /**
  31779. * Locks updates for the material.
  31780. */
  31781. Material.prototype.freeze = function () {
  31782. this.checkReadyOnlyOnce = true;
  31783. };
  31784. /**
  31785. * Unlocks updates for the material.
  31786. */
  31787. Material.prototype.unfreeze = function () {
  31788. this.checkReadyOnlyOnce = false;
  31789. };
  31790. /**
  31791. * Specifies if the material is ready to be used.
  31792. * @param mesh - BJS mesh.
  31793. * @param useInstances - Specifies if instances should be used.
  31794. * @returns - Boolean indicating if the material is ready to be used.
  31795. */
  31796. Material.prototype.isReady = function (mesh, useInstances) {
  31797. return true;
  31798. };
  31799. /**
  31800. * Specifies that the submesh is ready to be used.
  31801. * @param mesh - BJS mesh.
  31802. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31803. * @param useInstances - Specifies that instances should be used.
  31804. * @returns - boolean indicating that the submesh is ready or not.
  31805. */
  31806. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31807. return false;
  31808. };
  31809. /**
  31810. * Returns the material effect.
  31811. * @returns - Nullable material effect.
  31812. */
  31813. Material.prototype.getEffect = function () {
  31814. return this._effect;
  31815. };
  31816. /**
  31817. * Returns the BJS scene.
  31818. * @returns - BJS Scene.
  31819. */
  31820. Material.prototype.getScene = function () {
  31821. return this._scene;
  31822. };
  31823. /**
  31824. * Specifies if the material will require alpha blending
  31825. * @returns - Boolean specifying if alpha blending is needed.
  31826. */
  31827. Material.prototype.needAlphaBlending = function () {
  31828. return (this.alpha < 1.0);
  31829. };
  31830. /**
  31831. * Specifies if the mesh will require alpha blending.
  31832. * @param mesh - BJS mesh.
  31833. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31834. */
  31835. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31836. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31837. };
  31838. /**
  31839. * Specifies if this material should be rendered in alpha test mode.
  31840. * @returns - Boolean specifying if an alpha test is needed.
  31841. */
  31842. Material.prototype.needAlphaTesting = function () {
  31843. return false;
  31844. };
  31845. /**
  31846. * Gets the texture used for the alpha test.
  31847. * @returns - Nullable alpha test texture.
  31848. */
  31849. Material.prototype.getAlphaTestTexture = function () {
  31850. return null;
  31851. };
  31852. /**
  31853. * Marks the material to indicate that it needs to be re-calculated.
  31854. */
  31855. Material.prototype.markDirty = function () {
  31856. this._wasPreviouslyReady = false;
  31857. };
  31858. Material.prototype._preBind = function (effect, overrideOrientation) {
  31859. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31860. var engine = this._scene.getEngine();
  31861. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31862. var reverse = orientation === Material.ClockWiseSideOrientation;
  31863. engine.enableEffect(effect ? effect : this._effect);
  31864. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31865. return reverse;
  31866. };
  31867. /**
  31868. * Binds the material to the mesh.
  31869. * @param world - World transformation matrix.
  31870. * @param mesh - Mesh to bind the material to.
  31871. */
  31872. Material.prototype.bind = function (world, mesh) {
  31873. };
  31874. /**
  31875. * Binds the submesh to the material.
  31876. * @param world - World transformation matrix.
  31877. * @param mesh - Mesh containing the submesh.
  31878. * @param subMesh - Submesh to bind the material to.
  31879. */
  31880. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31881. };
  31882. /**
  31883. * Binds the world matrix to the material.
  31884. * @param world - World transformation matrix.
  31885. */
  31886. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31887. };
  31888. /**
  31889. * Binds the scene's uniform buffer to the effect.
  31890. * @param effect - Effect to bind to the scene uniform buffer.
  31891. * @param sceneUbo - Scene uniform buffer.
  31892. */
  31893. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31894. sceneUbo.bindToEffect(effect, "Scene");
  31895. };
  31896. /**
  31897. * Binds the view matrix to the effect.
  31898. * @param effect - Effect to bind the view matrix to.
  31899. */
  31900. Material.prototype.bindView = function (effect) {
  31901. if (!this._useUBO) {
  31902. effect.setMatrix("view", this.getScene().getViewMatrix());
  31903. }
  31904. else {
  31905. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31906. }
  31907. };
  31908. /**
  31909. * Binds the view projection matrix to the effect.
  31910. * @param effect - Effect to bind the view projection matrix to.
  31911. */
  31912. Material.prototype.bindViewProjection = function (effect) {
  31913. if (!this._useUBO) {
  31914. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31915. }
  31916. else {
  31917. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31918. }
  31919. };
  31920. /**
  31921. * Specifies if material alpha testing should be turned on for the mesh.
  31922. * @param mesh - BJS mesh.
  31923. */
  31924. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31925. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31926. };
  31927. /**
  31928. * Processes to execute after binding the material to a mesh.
  31929. * @param mesh - BJS mesh.
  31930. */
  31931. Material.prototype._afterBind = function (mesh) {
  31932. this._scene._cachedMaterial = this;
  31933. if (mesh) {
  31934. this._scene._cachedVisibility = mesh.visibility;
  31935. }
  31936. else {
  31937. this._scene._cachedVisibility = 1;
  31938. }
  31939. if (mesh) {
  31940. this.onBindObservable.notifyObservers(mesh);
  31941. }
  31942. if (this.disableDepthWrite) {
  31943. var engine = this._scene.getEngine();
  31944. this._cachedDepthWriteState = engine.getDepthWrite();
  31945. engine.setDepthWrite(false);
  31946. }
  31947. };
  31948. /**
  31949. * Unbinds the material from the mesh.
  31950. */
  31951. Material.prototype.unbind = function () {
  31952. this.onUnBindObservable.notifyObservers(this);
  31953. if (this.disableDepthWrite) {
  31954. var engine = this._scene.getEngine();
  31955. engine.setDepthWrite(this._cachedDepthWriteState);
  31956. }
  31957. };
  31958. /**
  31959. * Gets the active textures from the material.
  31960. * @returns - Array of textures.
  31961. */
  31962. Material.prototype.getActiveTextures = function () {
  31963. return [];
  31964. };
  31965. /**
  31966. * Specifies if the material uses a texture.
  31967. * @param texture - Texture to check against the material.
  31968. * @returns - Boolean specifying if the material uses the texture.
  31969. */
  31970. Material.prototype.hasTexture = function (texture) {
  31971. return false;
  31972. };
  31973. /**
  31974. * Makes a duplicate of the material, and gives it a new name.
  31975. * @param name - Name to call the duplicated material.
  31976. * @returns - Nullable cloned material
  31977. */
  31978. Material.prototype.clone = function (name) {
  31979. return null;
  31980. };
  31981. /**
  31982. * Gets the meshes bound to the material.
  31983. * @returns - Array of meshes bound to the material.
  31984. */
  31985. Material.prototype.getBindedMeshes = function () {
  31986. var result = new Array();
  31987. for (var index = 0; index < this._scene.meshes.length; index++) {
  31988. var mesh = this._scene.meshes[index];
  31989. if (mesh.material === this) {
  31990. result.push(mesh);
  31991. }
  31992. }
  31993. return result;
  31994. };
  31995. /**
  31996. * Force shader compilation
  31997. * @param mesh - BJS mesh.
  31998. * @param onCompiled - function to execute once the material is compiled.
  31999. * @param options - options to pass to this function.
  32000. */
  32001. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  32002. var _this = this;
  32003. var localOptions = __assign({ clipPlane: false }, options);
  32004. var subMesh = new BABYLON.BaseSubMesh();
  32005. var scene = this.getScene();
  32006. var checkReady = function () {
  32007. if (!_this._scene || !_this._scene.getEngine()) {
  32008. return;
  32009. }
  32010. if (subMesh._materialDefines) {
  32011. subMesh._materialDefines._renderId = -1;
  32012. }
  32013. var clipPlaneState = scene.clipPlane;
  32014. if (localOptions.clipPlane) {
  32015. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  32016. }
  32017. if (_this.storeEffectOnSubMeshes) {
  32018. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  32019. if (onCompiled) {
  32020. onCompiled(_this);
  32021. }
  32022. }
  32023. else {
  32024. setTimeout(checkReady, 16);
  32025. }
  32026. }
  32027. else {
  32028. if (_this.isReady(mesh)) {
  32029. if (onCompiled) {
  32030. onCompiled(_this);
  32031. }
  32032. }
  32033. else {
  32034. setTimeout(checkReady, 16);
  32035. }
  32036. }
  32037. if (localOptions.clipPlane) {
  32038. scene.clipPlane = clipPlaneState;
  32039. }
  32040. };
  32041. checkReady();
  32042. };
  32043. /**
  32044. * Force shader compilation.
  32045. * @param mesh The mesh that will use this material
  32046. * @param options Additional options for compiling the shaders
  32047. * @returns A promise that resolves when the compilation completes
  32048. */
  32049. Material.prototype.forceCompilationAsync = function (mesh, options) {
  32050. var _this = this;
  32051. return new Promise(function (resolve) {
  32052. _this.forceCompilation(mesh, function () {
  32053. resolve();
  32054. }, options);
  32055. });
  32056. };
  32057. /**
  32058. * Marks a define in the material to indicate that it needs to be re-computed.
  32059. * @param flag - Material define flag.
  32060. */
  32061. Material.prototype.markAsDirty = function (flag) {
  32062. if (flag & Material.TextureDirtyFlag) {
  32063. this._markAllSubMeshesAsTexturesDirty();
  32064. }
  32065. if (flag & Material.LightDirtyFlag) {
  32066. this._markAllSubMeshesAsLightsDirty();
  32067. }
  32068. if (flag & Material.FresnelDirtyFlag) {
  32069. this._markAllSubMeshesAsFresnelDirty();
  32070. }
  32071. if (flag & Material.AttributesDirtyFlag) {
  32072. this._markAllSubMeshesAsAttributesDirty();
  32073. }
  32074. if (flag & Material.MiscDirtyFlag) {
  32075. this._markAllSubMeshesAsMiscDirty();
  32076. }
  32077. this.getScene().resetCachedMaterial();
  32078. };
  32079. /**
  32080. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  32081. * @param func - function which checks material defines against the submeshes.
  32082. */
  32083. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  32084. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  32085. var mesh = _a[_i];
  32086. if (!mesh.subMeshes) {
  32087. continue;
  32088. }
  32089. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  32090. var subMesh = _c[_b];
  32091. if (subMesh.getMaterial() !== this) {
  32092. continue;
  32093. }
  32094. if (!subMesh._materialDefines) {
  32095. continue;
  32096. }
  32097. func(subMesh._materialDefines);
  32098. }
  32099. }
  32100. };
  32101. /**
  32102. * Indicates that image processing needs to be re-calculated for all submeshes.
  32103. */
  32104. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  32105. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  32106. };
  32107. /**
  32108. * Indicates that textures need to be re-calculated for all submeshes.
  32109. */
  32110. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  32111. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  32112. };
  32113. /**
  32114. * Indicates that fresnel needs to be re-calculated for all submeshes.
  32115. */
  32116. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  32117. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  32118. };
  32119. /**
  32120. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  32121. */
  32122. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  32123. this._markAllSubMeshesAsDirty(function (defines) {
  32124. defines.markAsFresnelDirty();
  32125. defines.markAsMiscDirty();
  32126. });
  32127. };
  32128. /**
  32129. * Indicates that lights need to be re-calculated for all submeshes.
  32130. */
  32131. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  32132. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  32133. };
  32134. /**
  32135. * Indicates that attributes need to be re-calculated for all submeshes.
  32136. */
  32137. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  32138. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  32139. };
  32140. /**
  32141. * Indicates that misc needs to be re-calculated for all submeshes.
  32142. */
  32143. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  32144. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  32145. };
  32146. /**
  32147. * Indicates that textures and misc need to be re-calculated for all submeshes.
  32148. */
  32149. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  32150. this._markAllSubMeshesAsDirty(function (defines) {
  32151. defines.markAsTexturesDirty();
  32152. defines.markAsMiscDirty();
  32153. });
  32154. };
  32155. /**
  32156. * Disposes the material.
  32157. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  32158. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  32159. */
  32160. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  32161. // Animations
  32162. this.getScene().stopAnimation(this);
  32163. this.getScene().freeProcessedMaterials();
  32164. // Remove from scene
  32165. var index = this._scene.materials.indexOf(this);
  32166. if (index >= 0) {
  32167. this._scene.materials.splice(index, 1);
  32168. }
  32169. // Remove from meshes
  32170. for (index = 0; index < this._scene.meshes.length; index++) {
  32171. var mesh = this._scene.meshes[index];
  32172. if (mesh.material === this) {
  32173. mesh.material = null;
  32174. if (mesh.geometry) {
  32175. var geometry = (mesh.geometry);
  32176. if (this.storeEffectOnSubMeshes) {
  32177. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  32178. var subMesh = _a[_i];
  32179. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  32180. if (forceDisposeEffect && subMesh._materialEffect) {
  32181. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  32182. }
  32183. }
  32184. }
  32185. else {
  32186. geometry._releaseVertexArrayObject(this._effect);
  32187. }
  32188. }
  32189. }
  32190. }
  32191. this._uniformBuffer.dispose();
  32192. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  32193. if (forceDisposeEffect && this._effect) {
  32194. if (!this.storeEffectOnSubMeshes) {
  32195. this._scene.getEngine()._releaseEffect(this._effect);
  32196. }
  32197. this._effect = null;
  32198. }
  32199. // Callback
  32200. this.onDisposeObservable.notifyObservers(this);
  32201. this.onDisposeObservable.clear();
  32202. this.onBindObservable.clear();
  32203. this.onUnBindObservable.clear();
  32204. };
  32205. /**
  32206. * Serializes this material.
  32207. * @returns - serialized material object.
  32208. */
  32209. Material.prototype.serialize = function () {
  32210. return BABYLON.SerializationHelper.Serialize(this);
  32211. };
  32212. /**
  32213. * Creates a MultiMaterial from parse MultiMaterial data.
  32214. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  32215. * @param scene - BJS scene.
  32216. * @returns - MultiMaterial.
  32217. */
  32218. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  32219. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  32220. multiMaterial.id = parsedMultiMaterial.id;
  32221. if (BABYLON.Tags) {
  32222. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  32223. }
  32224. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  32225. var subMatId = parsedMultiMaterial.materials[matIndex];
  32226. if (subMatId) {
  32227. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  32228. }
  32229. else {
  32230. multiMaterial.subMaterials.push(null);
  32231. }
  32232. }
  32233. return multiMaterial;
  32234. };
  32235. /**
  32236. * Creates a material from parsed material data.
  32237. * @param parsedMaterial - Parsed material data.
  32238. * @param scene - BJS scene.
  32239. * @param rootUrl - Root URL containing the material information.
  32240. * @returns - Parsed material.
  32241. */
  32242. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  32243. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  32244. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  32245. }
  32246. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  32247. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  32248. if (!BABYLON.LegacyPBRMaterial) {
  32249. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  32250. return;
  32251. }
  32252. }
  32253. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  32254. return materialType.Parse(parsedMaterial, scene, rootUrl);
  32255. ;
  32256. };
  32257. // Triangle views
  32258. Material._TriangleFillMode = 0;
  32259. Material._WireFrameFillMode = 1;
  32260. Material._PointFillMode = 2;
  32261. // Draw modes
  32262. Material._PointListDrawMode = 3;
  32263. Material._LineListDrawMode = 4;
  32264. Material._LineLoopDrawMode = 5;
  32265. Material._LineStripDrawMode = 6;
  32266. Material._TriangleStripDrawMode = 7;
  32267. Material._TriangleFanDrawMode = 8;
  32268. /**
  32269. * Stores the clock-wise side orientation.
  32270. */
  32271. Material._ClockWiseSideOrientation = 0;
  32272. /**
  32273. * Stores the counter clock-wise side orientation.
  32274. */
  32275. Material._CounterClockWiseSideOrientation = 1;
  32276. /**
  32277. * The dirty texture flag value.
  32278. */
  32279. Material._TextureDirtyFlag = 1;
  32280. /**
  32281. * The dirty light flag value.
  32282. */
  32283. Material._LightDirtyFlag = 2;
  32284. /**
  32285. * The dirty fresnel flag value.
  32286. */
  32287. Material._FresnelDirtyFlag = 4;
  32288. /**
  32289. * The dirty attribute flag value.
  32290. */
  32291. Material._AttributesDirtyFlag = 8;
  32292. /**
  32293. * The dirty misc flag value.
  32294. */
  32295. Material._MiscDirtyFlag = 16;
  32296. __decorate([
  32297. BABYLON.serialize()
  32298. ], Material.prototype, "id", void 0);
  32299. __decorate([
  32300. BABYLON.serialize()
  32301. ], Material.prototype, "name", void 0);
  32302. __decorate([
  32303. BABYLON.serialize()
  32304. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  32305. __decorate([
  32306. BABYLON.serialize()
  32307. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  32308. __decorate([
  32309. BABYLON.serialize()
  32310. ], Material.prototype, "state", void 0);
  32311. __decorate([
  32312. BABYLON.serialize("alpha")
  32313. ], Material.prototype, "_alpha", void 0);
  32314. __decorate([
  32315. BABYLON.serialize("backFaceCulling")
  32316. ], Material.prototype, "_backFaceCulling", void 0);
  32317. __decorate([
  32318. BABYLON.serialize()
  32319. ], Material.prototype, "sideOrientation", void 0);
  32320. __decorate([
  32321. BABYLON.serialize("alphaMode")
  32322. ], Material.prototype, "_alphaMode", void 0);
  32323. __decorate([
  32324. BABYLON.serialize()
  32325. ], Material.prototype, "_needDepthPrePass", void 0);
  32326. __decorate([
  32327. BABYLON.serialize()
  32328. ], Material.prototype, "disableDepthWrite", void 0);
  32329. __decorate([
  32330. BABYLON.serialize()
  32331. ], Material.prototype, "forceDepthWrite", void 0);
  32332. __decorate([
  32333. BABYLON.serialize()
  32334. ], Material.prototype, "separateCullingPass", void 0);
  32335. __decorate([
  32336. BABYLON.serialize("fogEnabled")
  32337. ], Material.prototype, "_fogEnabled", void 0);
  32338. __decorate([
  32339. BABYLON.serialize()
  32340. ], Material.prototype, "pointSize", void 0);
  32341. __decorate([
  32342. BABYLON.serialize()
  32343. ], Material.prototype, "zOffset", void 0);
  32344. __decorate([
  32345. BABYLON.serialize()
  32346. ], Material.prototype, "wireframe", null);
  32347. __decorate([
  32348. BABYLON.serialize()
  32349. ], Material.prototype, "pointsCloud", null);
  32350. __decorate([
  32351. BABYLON.serialize()
  32352. ], Material.prototype, "fillMode", null);
  32353. return Material;
  32354. }());
  32355. BABYLON.Material = Material;
  32356. })(BABYLON || (BABYLON = {}));
  32357. //# sourceMappingURL=babylon.material.js.map
  32358. "use strict";
  32359. var BABYLON;
  32360. (function (BABYLON) {
  32361. var UniformBuffer = /** @class */ (function () {
  32362. /**
  32363. * Uniform buffer objects.
  32364. *
  32365. * Handles blocks of uniform on the GPU.
  32366. *
  32367. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  32368. *
  32369. * For more information, please refer to :
  32370. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  32371. */
  32372. function UniformBuffer(engine, data, dynamic) {
  32373. this._engine = engine;
  32374. this._noUBO = !engine.supportsUniformBuffers;
  32375. this._dynamic = dynamic;
  32376. this._data = data || [];
  32377. this._uniformLocations = {};
  32378. this._uniformSizes = {};
  32379. this._uniformLocationPointer = 0;
  32380. this._needSync = false;
  32381. if (this._noUBO) {
  32382. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  32383. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  32384. this.updateFloat = this._updateFloatForEffect;
  32385. this.updateFloat2 = this._updateFloat2ForEffect;
  32386. this.updateFloat3 = this._updateFloat3ForEffect;
  32387. this.updateFloat4 = this._updateFloat4ForEffect;
  32388. this.updateMatrix = this._updateMatrixForEffect;
  32389. this.updateVector3 = this._updateVector3ForEffect;
  32390. this.updateVector4 = this._updateVector4ForEffect;
  32391. this.updateColor3 = this._updateColor3ForEffect;
  32392. this.updateColor4 = this._updateColor4ForEffect;
  32393. }
  32394. else {
  32395. this._engine._uniformBuffers.push(this);
  32396. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  32397. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  32398. this.updateFloat = this._updateFloatForUniform;
  32399. this.updateFloat2 = this._updateFloat2ForUniform;
  32400. this.updateFloat3 = this._updateFloat3ForUniform;
  32401. this.updateFloat4 = this._updateFloat4ForUniform;
  32402. this.updateMatrix = this._updateMatrixForUniform;
  32403. this.updateVector3 = this._updateVector3ForUniform;
  32404. this.updateVector4 = this._updateVector4ForUniform;
  32405. this.updateColor3 = this._updateColor3ForUniform;
  32406. this.updateColor4 = this._updateColor4ForUniform;
  32407. }
  32408. }
  32409. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  32410. // Properties
  32411. /**
  32412. * Indicates if the buffer is using the WebGL2 UBO implementation,
  32413. * or just falling back on setUniformXXX calls.
  32414. */
  32415. get: function () {
  32416. return !this._noUBO;
  32417. },
  32418. enumerable: true,
  32419. configurable: true
  32420. });
  32421. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  32422. /**
  32423. * Indicates if the WebGL underlying uniform buffer is in sync
  32424. * with the javascript cache data.
  32425. */
  32426. get: function () {
  32427. return !this._needSync;
  32428. },
  32429. enumerable: true,
  32430. configurable: true
  32431. });
  32432. /**
  32433. * Indicates if the WebGL underlying uniform buffer is dynamic.
  32434. * Also, a dynamic UniformBuffer will disable cache verification and always
  32435. * update the underlying WebGL uniform buffer to the GPU.
  32436. */
  32437. UniformBuffer.prototype.isDynamic = function () {
  32438. return this._dynamic !== undefined;
  32439. };
  32440. /**
  32441. * The data cache on JS side.
  32442. */
  32443. UniformBuffer.prototype.getData = function () {
  32444. return this._bufferData;
  32445. };
  32446. /**
  32447. * The underlying WebGL Uniform buffer.
  32448. */
  32449. UniformBuffer.prototype.getBuffer = function () {
  32450. return this._buffer;
  32451. };
  32452. /**
  32453. * std140 layout specifies how to align data within an UBO structure.
  32454. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  32455. * for specs.
  32456. */
  32457. UniformBuffer.prototype._fillAlignment = function (size) {
  32458. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  32459. // and 4x4 matrices
  32460. // TODO : change if other types are used
  32461. var alignment;
  32462. if (size <= 2) {
  32463. alignment = size;
  32464. }
  32465. else {
  32466. alignment = 4;
  32467. }
  32468. if ((this._uniformLocationPointer % alignment) !== 0) {
  32469. var oldPointer = this._uniformLocationPointer;
  32470. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  32471. var diff = this._uniformLocationPointer - oldPointer;
  32472. for (var i = 0; i < diff; i++) {
  32473. this._data.push(0);
  32474. }
  32475. }
  32476. };
  32477. /**
  32478. * Adds an uniform in the buffer.
  32479. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  32480. * for the layout to be correct !
  32481. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32482. * @param {number|number[]} size Data size, or data directly.
  32483. */
  32484. UniformBuffer.prototype.addUniform = function (name, size) {
  32485. if (this._noUBO) {
  32486. return;
  32487. }
  32488. if (this._uniformLocations[name] !== undefined) {
  32489. // Already existing uniform
  32490. return;
  32491. }
  32492. // This function must be called in the order of the shader layout !
  32493. // size can be the size of the uniform, or data directly
  32494. var data;
  32495. if (size instanceof Array) {
  32496. data = size;
  32497. size = data.length;
  32498. }
  32499. else {
  32500. size = size;
  32501. data = [];
  32502. // Fill with zeros
  32503. for (var i = 0; i < size; i++) {
  32504. data.push(0);
  32505. }
  32506. }
  32507. this._fillAlignment(size);
  32508. this._uniformSizes[name] = size;
  32509. this._uniformLocations[name] = this._uniformLocationPointer;
  32510. this._uniformLocationPointer += size;
  32511. for (var i = 0; i < size; i++) {
  32512. this._data.push(data[i]);
  32513. }
  32514. this._needSync = true;
  32515. };
  32516. /**
  32517. * Wrapper for addUniform.
  32518. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32519. * @param {Matrix} mat A 4x4 matrix.
  32520. */
  32521. UniformBuffer.prototype.addMatrix = function (name, mat) {
  32522. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  32523. };
  32524. /**
  32525. * Wrapper for addUniform.
  32526. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32527. * @param {number} x
  32528. * @param {number} y
  32529. */
  32530. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  32531. var temp = [x, y];
  32532. this.addUniform(name, temp);
  32533. };
  32534. /**
  32535. * Wrapper for addUniform.
  32536. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32537. * @param {number} x
  32538. * @param {number} y
  32539. * @param {number} z
  32540. */
  32541. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  32542. var temp = [x, y, z];
  32543. this.addUniform(name, temp);
  32544. };
  32545. /**
  32546. * Wrapper for addUniform.
  32547. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32548. * @param {Color3} color
  32549. */
  32550. UniformBuffer.prototype.addColor3 = function (name, color) {
  32551. var temp = new Array();
  32552. color.toArray(temp);
  32553. this.addUniform(name, temp);
  32554. };
  32555. /**
  32556. * Wrapper for addUniform.
  32557. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32558. * @param {Color3} color
  32559. * @param {number} alpha
  32560. */
  32561. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  32562. var temp = new Array();
  32563. color.toArray(temp);
  32564. temp.push(alpha);
  32565. this.addUniform(name, temp);
  32566. };
  32567. /**
  32568. * Wrapper for addUniform.
  32569. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32570. * @param {Vector3} vector
  32571. */
  32572. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32573. var temp = new Array();
  32574. vector.toArray(temp);
  32575. this.addUniform(name, temp);
  32576. };
  32577. /**
  32578. * Wrapper for addUniform.
  32579. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32580. */
  32581. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32582. this.addUniform(name, 12);
  32583. };
  32584. /**
  32585. * Wrapper for addUniform.
  32586. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32587. */
  32588. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32589. this.addUniform(name, 8);
  32590. };
  32591. /**
  32592. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32593. */
  32594. UniformBuffer.prototype.create = function () {
  32595. if (this._noUBO) {
  32596. return;
  32597. }
  32598. if (this._buffer) {
  32599. return; // nothing to do
  32600. }
  32601. // See spec, alignment must be filled as a vec4
  32602. this._fillAlignment(4);
  32603. this._bufferData = new Float32Array(this._data);
  32604. this._rebuild();
  32605. this._needSync = true;
  32606. };
  32607. UniformBuffer.prototype._rebuild = function () {
  32608. if (this._noUBO) {
  32609. return;
  32610. }
  32611. if (this._dynamic) {
  32612. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32613. }
  32614. else {
  32615. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32616. }
  32617. };
  32618. /**
  32619. * Updates the WebGL Uniform Buffer on the GPU.
  32620. * If the `dynamic` flag is set to true, no cache comparison is done.
  32621. * Otherwise, the buffer will be updated only if the cache differs.
  32622. */
  32623. UniformBuffer.prototype.update = function () {
  32624. if (!this._buffer) {
  32625. this.create();
  32626. return;
  32627. }
  32628. if (!this._dynamic && !this._needSync) {
  32629. return;
  32630. }
  32631. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32632. this._needSync = false;
  32633. };
  32634. /**
  32635. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32636. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32637. * @param {number[]|Float32Array} data Flattened data
  32638. * @param {number} size Size of the data.
  32639. */
  32640. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32641. var location = this._uniformLocations[uniformName];
  32642. if (location === undefined) {
  32643. if (this._buffer) {
  32644. // Cannot add an uniform if the buffer is already created
  32645. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32646. return;
  32647. }
  32648. this.addUniform(uniformName, size);
  32649. location = this._uniformLocations[uniformName];
  32650. }
  32651. if (!this._buffer) {
  32652. this.create();
  32653. }
  32654. if (!this._dynamic) {
  32655. // Cache for static uniform buffers
  32656. var changed = false;
  32657. for (var i = 0; i < size; i++) {
  32658. if (this._bufferData[location + i] !== data[i]) {
  32659. changed = true;
  32660. this._bufferData[location + i] = data[i];
  32661. }
  32662. }
  32663. this._needSync = this._needSync || changed;
  32664. }
  32665. else {
  32666. // No cache for dynamic
  32667. for (var i = 0; i < size; i++) {
  32668. this._bufferData[location + i] = data[i];
  32669. }
  32670. }
  32671. };
  32672. // Update methods
  32673. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32674. // To match std140, matrix must be realigned
  32675. for (var i = 0; i < 3; i++) {
  32676. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32677. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32678. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32679. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32680. }
  32681. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32682. };
  32683. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32684. this._currentEffect.setMatrix3x3(name, matrix);
  32685. };
  32686. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32687. this._currentEffect.setMatrix2x2(name, matrix);
  32688. };
  32689. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32690. // To match std140, matrix must be realigned
  32691. for (var i = 0; i < 2; i++) {
  32692. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32693. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32694. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32695. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32696. }
  32697. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32698. };
  32699. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32700. this._currentEffect.setFloat(name, x);
  32701. };
  32702. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32703. UniformBuffer._tempBuffer[0] = x;
  32704. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32705. };
  32706. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32707. if (suffix === void 0) { suffix = ""; }
  32708. this._currentEffect.setFloat2(name + suffix, x, y);
  32709. };
  32710. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32711. if (suffix === void 0) { suffix = ""; }
  32712. UniformBuffer._tempBuffer[0] = x;
  32713. UniformBuffer._tempBuffer[1] = y;
  32714. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32715. };
  32716. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32717. if (suffix === void 0) { suffix = ""; }
  32718. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32719. };
  32720. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32721. if (suffix === void 0) { suffix = ""; }
  32722. UniformBuffer._tempBuffer[0] = x;
  32723. UniformBuffer._tempBuffer[1] = y;
  32724. UniformBuffer._tempBuffer[2] = z;
  32725. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32726. };
  32727. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32728. if (suffix === void 0) { suffix = ""; }
  32729. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32730. };
  32731. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32732. if (suffix === void 0) { suffix = ""; }
  32733. UniformBuffer._tempBuffer[0] = x;
  32734. UniformBuffer._tempBuffer[1] = y;
  32735. UniformBuffer._tempBuffer[2] = z;
  32736. UniformBuffer._tempBuffer[3] = w;
  32737. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32738. };
  32739. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32740. this._currentEffect.setMatrix(name, mat);
  32741. };
  32742. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32743. this.updateUniform(name, mat.toArray(), 16);
  32744. };
  32745. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32746. this._currentEffect.setVector3(name, vector);
  32747. };
  32748. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32749. vector.toArray(UniformBuffer._tempBuffer);
  32750. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32751. };
  32752. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32753. this._currentEffect.setVector4(name, vector);
  32754. };
  32755. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32756. vector.toArray(UniformBuffer._tempBuffer);
  32757. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32758. };
  32759. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32760. if (suffix === void 0) { suffix = ""; }
  32761. this._currentEffect.setColor3(name + suffix, color);
  32762. };
  32763. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32764. if (suffix === void 0) { suffix = ""; }
  32765. color.toArray(UniformBuffer._tempBuffer);
  32766. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32767. };
  32768. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32769. if (suffix === void 0) { suffix = ""; }
  32770. this._currentEffect.setColor4(name + suffix, color, alpha);
  32771. };
  32772. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32773. if (suffix === void 0) { suffix = ""; }
  32774. color.toArray(UniformBuffer._tempBuffer);
  32775. UniformBuffer._tempBuffer[3] = alpha;
  32776. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32777. };
  32778. /**
  32779. * Sets a sampler uniform on the effect.
  32780. * @param {string} name Name of the sampler.
  32781. * @param {Texture} texture
  32782. */
  32783. UniformBuffer.prototype.setTexture = function (name, texture) {
  32784. this._currentEffect.setTexture(name, texture);
  32785. };
  32786. /**
  32787. * Directly updates the value of the uniform in the cache AND on the GPU.
  32788. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32789. * @param {number[]|Float32Array} data Flattened data
  32790. */
  32791. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32792. this.updateUniform(uniformName, data, data.length);
  32793. this.update();
  32794. };
  32795. /**
  32796. * Binds this uniform buffer to an effect.
  32797. * @param {Effect} effect
  32798. * @param {string} name Name of the uniform block in the shader.
  32799. */
  32800. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32801. this._currentEffect = effect;
  32802. if (this._noUBO || !this._buffer) {
  32803. return;
  32804. }
  32805. effect.bindUniformBuffer(this._buffer, name);
  32806. };
  32807. /**
  32808. * Disposes the uniform buffer.
  32809. */
  32810. UniformBuffer.prototype.dispose = function () {
  32811. if (this._noUBO) {
  32812. return;
  32813. }
  32814. var index = this._engine._uniformBuffers.indexOf(this);
  32815. if (index !== -1) {
  32816. this._engine._uniformBuffers.splice(index, 1);
  32817. }
  32818. if (!this._buffer) {
  32819. return;
  32820. }
  32821. if (this._engine._releaseBuffer(this._buffer)) {
  32822. this._buffer = null;
  32823. }
  32824. };
  32825. // Pool for avoiding memory leaks
  32826. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32827. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32828. return UniformBuffer;
  32829. }());
  32830. BABYLON.UniformBuffer = UniformBuffer;
  32831. })(BABYLON || (BABYLON = {}));
  32832. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32833. "use strict";
  32834. var BABYLON;
  32835. (function (BABYLON) {
  32836. var VertexData = /** @class */ (function () {
  32837. function VertexData() {
  32838. }
  32839. VertexData.prototype.set = function (data, kind) {
  32840. switch (kind) {
  32841. case BABYLON.VertexBuffer.PositionKind:
  32842. this.positions = data;
  32843. break;
  32844. case BABYLON.VertexBuffer.NormalKind:
  32845. this.normals = data;
  32846. break;
  32847. case BABYLON.VertexBuffer.TangentKind:
  32848. this.tangents = data;
  32849. break;
  32850. case BABYLON.VertexBuffer.UVKind:
  32851. this.uvs = data;
  32852. break;
  32853. case BABYLON.VertexBuffer.UV2Kind:
  32854. this.uvs2 = data;
  32855. break;
  32856. case BABYLON.VertexBuffer.UV3Kind:
  32857. this.uvs3 = data;
  32858. break;
  32859. case BABYLON.VertexBuffer.UV4Kind:
  32860. this.uvs4 = data;
  32861. break;
  32862. case BABYLON.VertexBuffer.UV5Kind:
  32863. this.uvs5 = data;
  32864. break;
  32865. case BABYLON.VertexBuffer.UV6Kind:
  32866. this.uvs6 = data;
  32867. break;
  32868. case BABYLON.VertexBuffer.ColorKind:
  32869. this.colors = data;
  32870. break;
  32871. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32872. this.matricesIndices = data;
  32873. break;
  32874. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32875. this.matricesWeights = data;
  32876. break;
  32877. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32878. this.matricesIndicesExtra = data;
  32879. break;
  32880. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32881. this.matricesWeightsExtra = data;
  32882. break;
  32883. }
  32884. };
  32885. /**
  32886. * Associates the vertexData to the passed Mesh.
  32887. * Sets it as updatable or not (default `false`).
  32888. * Returns the VertexData.
  32889. */
  32890. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32891. this._applyTo(mesh, updatable);
  32892. return this;
  32893. };
  32894. /**
  32895. * Associates the vertexData to the passed Geometry.
  32896. * Sets it as updatable or not (default `false`).
  32897. * Returns the VertexData.
  32898. */
  32899. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32900. this._applyTo(geometry, updatable);
  32901. return this;
  32902. };
  32903. /**
  32904. * Updates the associated mesh.
  32905. * Returns the VertexData.
  32906. */
  32907. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32908. this._update(mesh);
  32909. return this;
  32910. };
  32911. /**
  32912. * Updates the associated geometry.
  32913. * Returns the VertexData.
  32914. */
  32915. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32916. this._update(geometry);
  32917. return this;
  32918. };
  32919. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32920. if (updatable === void 0) { updatable = false; }
  32921. if (this.positions) {
  32922. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32923. }
  32924. if (this.normals) {
  32925. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32926. }
  32927. if (this.tangents) {
  32928. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32929. }
  32930. if (this.uvs) {
  32931. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32932. }
  32933. if (this.uvs2) {
  32934. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32935. }
  32936. if (this.uvs3) {
  32937. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32938. }
  32939. if (this.uvs4) {
  32940. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32941. }
  32942. if (this.uvs5) {
  32943. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32944. }
  32945. if (this.uvs6) {
  32946. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32947. }
  32948. if (this.colors) {
  32949. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32950. }
  32951. if (this.matricesIndices) {
  32952. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32953. }
  32954. if (this.matricesWeights) {
  32955. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32956. }
  32957. if (this.matricesIndicesExtra) {
  32958. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32959. }
  32960. if (this.matricesWeightsExtra) {
  32961. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32962. }
  32963. if (this.indices) {
  32964. meshOrGeometry.setIndices(this.indices, null, updatable);
  32965. }
  32966. return this;
  32967. };
  32968. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32969. if (this.positions) {
  32970. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32971. }
  32972. if (this.normals) {
  32973. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32974. }
  32975. if (this.tangents) {
  32976. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  32977. }
  32978. if (this.uvs) {
  32979. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32980. }
  32981. if (this.uvs2) {
  32982. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32983. }
  32984. if (this.uvs3) {
  32985. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32986. }
  32987. if (this.uvs4) {
  32988. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32989. }
  32990. if (this.uvs5) {
  32991. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32992. }
  32993. if (this.uvs6) {
  32994. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32995. }
  32996. if (this.colors) {
  32997. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32998. }
  32999. if (this.matricesIndices) {
  33000. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  33001. }
  33002. if (this.matricesWeights) {
  33003. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  33004. }
  33005. if (this.matricesIndicesExtra) {
  33006. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  33007. }
  33008. if (this.matricesWeightsExtra) {
  33009. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  33010. }
  33011. if (this.indices) {
  33012. meshOrGeometry.setIndices(this.indices, null);
  33013. }
  33014. return this;
  33015. };
  33016. /**
  33017. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  33018. * Returns the VertexData.
  33019. */
  33020. VertexData.prototype.transform = function (matrix) {
  33021. var transformed = BABYLON.Vector3.Zero();
  33022. var index;
  33023. if (this.positions) {
  33024. var position = BABYLON.Vector3.Zero();
  33025. for (index = 0; index < this.positions.length; index += 3) {
  33026. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  33027. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  33028. this.positions[index] = transformed.x;
  33029. this.positions[index + 1] = transformed.y;
  33030. this.positions[index + 2] = transformed.z;
  33031. }
  33032. }
  33033. if (this.normals) {
  33034. var normal = BABYLON.Vector3.Zero();
  33035. for (index = 0; index < this.normals.length; index += 3) {
  33036. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  33037. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  33038. this.normals[index] = transformed.x;
  33039. this.normals[index + 1] = transformed.y;
  33040. this.normals[index + 2] = transformed.z;
  33041. }
  33042. }
  33043. if (this.tangents) {
  33044. var tangent = BABYLON.Vector4.Zero();
  33045. var tangentTransformed = BABYLON.Vector4.Zero();
  33046. for (index = 0; index < this.tangents.length; index += 4) {
  33047. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  33048. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  33049. this.tangents[index] = tangentTransformed.x;
  33050. this.tangents[index + 1] = tangentTransformed.y;
  33051. this.tangents[index + 2] = tangentTransformed.z;
  33052. this.tangents[index + 3] = tangentTransformed.w;
  33053. }
  33054. }
  33055. return this;
  33056. };
  33057. /**
  33058. * Merges the passed VertexData into the current one.
  33059. * Returns the modified VertexData.
  33060. */
  33061. VertexData.prototype.merge = function (other) {
  33062. this._validate();
  33063. other._validate();
  33064. if (!this.normals !== !other.normals ||
  33065. !this.tangents !== !other.tangents ||
  33066. !this.uvs !== !other.uvs ||
  33067. !this.uvs2 !== !other.uvs2 ||
  33068. !this.uvs3 !== !other.uvs3 ||
  33069. !this.uvs4 !== !other.uvs4 ||
  33070. !this.uvs5 !== !other.uvs5 ||
  33071. !this.uvs6 !== !other.uvs6 ||
  33072. !this.colors !== !other.colors ||
  33073. !this.matricesIndices !== !other.matricesIndices ||
  33074. !this.matricesWeights !== !other.matricesWeights ||
  33075. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  33076. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  33077. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  33078. }
  33079. if (other.indices) {
  33080. if (!this.indices) {
  33081. this.indices = [];
  33082. }
  33083. var offset = this.positions ? this.positions.length / 3 : 0;
  33084. for (var index = 0; index < other.indices.length; index++) {
  33085. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  33086. this.indices.push(other.indices[index] + offset);
  33087. }
  33088. }
  33089. this.positions = this._mergeElement(this.positions, other.positions);
  33090. this.normals = this._mergeElement(this.normals, other.normals);
  33091. this.tangents = this._mergeElement(this.tangents, other.tangents);
  33092. this.uvs = this._mergeElement(this.uvs, other.uvs);
  33093. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  33094. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  33095. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  33096. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  33097. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  33098. this.colors = this._mergeElement(this.colors, other.colors);
  33099. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  33100. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  33101. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  33102. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  33103. return this;
  33104. };
  33105. VertexData.prototype._mergeElement = function (source, other) {
  33106. if (!source) {
  33107. return other;
  33108. }
  33109. if (!other) {
  33110. return source;
  33111. }
  33112. var len = other.length + source.length;
  33113. var isSrcTypedArray = source instanceof Float32Array;
  33114. var isOthTypedArray = other instanceof Float32Array;
  33115. // use non-loop method when the source is Float32Array
  33116. if (isSrcTypedArray) {
  33117. var ret32 = new Float32Array(len);
  33118. ret32.set(source);
  33119. ret32.set(other, source.length);
  33120. return ret32;
  33121. // source is number[], when other is also use concat
  33122. }
  33123. else if (!isOthTypedArray) {
  33124. return source.concat(other);
  33125. // source is a number[], but other is a Float32Array, loop required
  33126. }
  33127. else {
  33128. var ret = source.slice(0); // copy source to a separate array
  33129. for (var i = 0, len = other.length; i < len; i++) {
  33130. ret.push(other[i]);
  33131. }
  33132. return ret;
  33133. }
  33134. };
  33135. VertexData.prototype._validate = function () {
  33136. if (!this.positions) {
  33137. throw new Error("Positions are required");
  33138. }
  33139. var getElementCount = function (kind, values) {
  33140. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  33141. if ((values.length % stride) !== 0) {
  33142. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  33143. }
  33144. return values.length / stride;
  33145. };
  33146. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  33147. var validateElementCount = function (kind, values) {
  33148. var elementCount = getElementCount(kind, values);
  33149. if (elementCount !== positionsElementCount) {
  33150. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  33151. }
  33152. };
  33153. if (this.normals)
  33154. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  33155. if (this.tangents)
  33156. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  33157. if (this.uvs)
  33158. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  33159. if (this.uvs2)
  33160. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  33161. if (this.uvs3)
  33162. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  33163. if (this.uvs4)
  33164. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  33165. if (this.uvs5)
  33166. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  33167. if (this.uvs6)
  33168. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  33169. if (this.colors)
  33170. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  33171. if (this.matricesIndices)
  33172. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  33173. if (this.matricesWeights)
  33174. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  33175. if (this.matricesIndicesExtra)
  33176. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  33177. if (this.matricesWeightsExtra)
  33178. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  33179. };
  33180. /**
  33181. * Serializes the VertexData.
  33182. * Returns a serialized object.
  33183. */
  33184. VertexData.prototype.serialize = function () {
  33185. var serializationObject = this.serialize();
  33186. if (this.positions) {
  33187. serializationObject.positions = this.positions;
  33188. }
  33189. if (this.normals) {
  33190. serializationObject.normals = this.normals;
  33191. }
  33192. if (this.tangents) {
  33193. serializationObject.tangents = this.tangents;
  33194. }
  33195. if (this.uvs) {
  33196. serializationObject.uvs = this.uvs;
  33197. }
  33198. if (this.uvs2) {
  33199. serializationObject.uvs2 = this.uvs2;
  33200. }
  33201. if (this.uvs3) {
  33202. serializationObject.uvs3 = this.uvs3;
  33203. }
  33204. if (this.uvs4) {
  33205. serializationObject.uvs4 = this.uvs4;
  33206. }
  33207. if (this.uvs5) {
  33208. serializationObject.uvs5 = this.uvs5;
  33209. }
  33210. if (this.uvs6) {
  33211. serializationObject.uvs6 = this.uvs6;
  33212. }
  33213. if (this.colors) {
  33214. serializationObject.colors = this.colors;
  33215. }
  33216. if (this.matricesIndices) {
  33217. serializationObject.matricesIndices = this.matricesIndices;
  33218. serializationObject.matricesIndices._isExpanded = true;
  33219. }
  33220. if (this.matricesWeights) {
  33221. serializationObject.matricesWeights = this.matricesWeights;
  33222. }
  33223. if (this.matricesIndicesExtra) {
  33224. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  33225. serializationObject.matricesIndicesExtra._isExpanded = true;
  33226. }
  33227. if (this.matricesWeightsExtra) {
  33228. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  33229. }
  33230. serializationObject.indices = this.indices;
  33231. return serializationObject;
  33232. };
  33233. // Statics
  33234. /**
  33235. * Returns the object VertexData associated to the passed mesh.
  33236. */
  33237. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  33238. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  33239. };
  33240. /**
  33241. * Returns the object VertexData associated to the passed geometry.
  33242. */
  33243. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  33244. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  33245. };
  33246. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  33247. var result = new VertexData();
  33248. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33249. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  33250. }
  33251. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33252. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  33253. }
  33254. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  33255. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  33256. }
  33257. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33258. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  33259. }
  33260. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33261. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  33262. }
  33263. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33264. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  33265. }
  33266. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33267. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  33268. }
  33269. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33270. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  33271. }
  33272. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33273. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  33274. }
  33275. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33276. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  33277. }
  33278. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33279. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  33280. }
  33281. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33282. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  33283. }
  33284. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  33285. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  33286. }
  33287. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33288. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  33289. }
  33290. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  33291. return result;
  33292. };
  33293. /**
  33294. * Creates the vertexData of the Ribbon.
  33295. */
  33296. VertexData.CreateRibbon = function (options) {
  33297. var pathArray = options.pathArray;
  33298. var closeArray = options.closeArray || false;
  33299. var closePath = options.closePath || false;
  33300. var invertUV = options.invertUV || false;
  33301. var defaultOffset = Math.floor(pathArray[0].length / 2);
  33302. var offset = options.offset || defaultOffset;
  33303. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  33304. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33305. var customUV = options.uvs;
  33306. var customColors = options.colors;
  33307. var positions = [];
  33308. var indices = [];
  33309. var normals = [];
  33310. var uvs = [];
  33311. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  33312. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  33313. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  33314. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  33315. var minlg; // minimal length among all paths from pathArray
  33316. var lg = []; // array of path lengths : nb of vertex per path
  33317. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  33318. var p; // path iterator
  33319. var i; // point iterator
  33320. var j; // point iterator
  33321. // if single path in pathArray
  33322. if (pathArray.length < 2) {
  33323. var ar1 = [];
  33324. var ar2 = [];
  33325. for (i = 0; i < pathArray[0].length - offset; i++) {
  33326. ar1.push(pathArray[0][i]);
  33327. ar2.push(pathArray[0][i + offset]);
  33328. }
  33329. pathArray = [ar1, ar2];
  33330. }
  33331. // positions and horizontal distances (u)
  33332. var idc = 0;
  33333. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  33334. var path;
  33335. var l;
  33336. minlg = pathArray[0].length;
  33337. var vectlg;
  33338. var dist;
  33339. for (p = 0; p < pathArray.length; p++) {
  33340. uTotalDistance[p] = 0;
  33341. us[p] = [0];
  33342. path = pathArray[p];
  33343. l = path.length;
  33344. minlg = (minlg < l) ? minlg : l;
  33345. j = 0;
  33346. while (j < l) {
  33347. positions.push(path[j].x, path[j].y, path[j].z);
  33348. if (j > 0) {
  33349. vectlg = path[j].subtract(path[j - 1]).length();
  33350. dist = vectlg + uTotalDistance[p];
  33351. us[p].push(dist);
  33352. uTotalDistance[p] = dist;
  33353. }
  33354. j++;
  33355. }
  33356. if (closePath) {
  33357. j--;
  33358. positions.push(path[0].x, path[0].y, path[0].z);
  33359. vectlg = path[j].subtract(path[0]).length();
  33360. dist = vectlg + uTotalDistance[p];
  33361. us[p].push(dist);
  33362. uTotalDistance[p] = dist;
  33363. }
  33364. lg[p] = l + closePathCorr;
  33365. idx[p] = idc;
  33366. idc += (l + closePathCorr);
  33367. }
  33368. // vertical distances (v)
  33369. var path1;
  33370. var path2;
  33371. var vertex1 = null;
  33372. var vertex2 = null;
  33373. for (i = 0; i < minlg + closePathCorr; i++) {
  33374. vTotalDistance[i] = 0;
  33375. vs[i] = [0];
  33376. for (p = 0; p < pathArray.length - 1; p++) {
  33377. path1 = pathArray[p];
  33378. path2 = pathArray[p + 1];
  33379. if (i === minlg) {
  33380. vertex1 = path1[0];
  33381. vertex2 = path2[0];
  33382. }
  33383. else {
  33384. vertex1 = path1[i];
  33385. vertex2 = path2[i];
  33386. }
  33387. vectlg = vertex2.subtract(vertex1).length();
  33388. dist = vectlg + vTotalDistance[i];
  33389. vs[i].push(dist);
  33390. vTotalDistance[i] = dist;
  33391. }
  33392. if (closeArray && vertex2 && vertex1) {
  33393. path1 = pathArray[p];
  33394. path2 = pathArray[0];
  33395. if (i === minlg) {
  33396. vertex2 = path2[0];
  33397. }
  33398. vectlg = vertex2.subtract(vertex1).length();
  33399. dist = vectlg + vTotalDistance[i];
  33400. vTotalDistance[i] = dist;
  33401. }
  33402. }
  33403. // uvs
  33404. var u;
  33405. var v;
  33406. if (customUV) {
  33407. for (p = 0; p < customUV.length; p++) {
  33408. uvs.push(customUV[p].x, customUV[p].y);
  33409. }
  33410. }
  33411. else {
  33412. for (p = 0; p < pathArray.length; p++) {
  33413. for (i = 0; i < minlg + closePathCorr; i++) {
  33414. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  33415. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  33416. if (invertUV) {
  33417. uvs.push(v, u);
  33418. }
  33419. else {
  33420. uvs.push(u, v);
  33421. }
  33422. }
  33423. }
  33424. }
  33425. // indices
  33426. p = 0; // path index
  33427. var pi = 0; // positions array index
  33428. var l1 = lg[p] - 1; // path1 length
  33429. var l2 = lg[p + 1] - 1; // path2 length
  33430. var min = (l1 < l2) ? l1 : l2; // current path stop index
  33431. var shft = idx[1] - idx[0]; // shift
  33432. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  33433. while (pi <= min && p < path1nb) {
  33434. // 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
  33435. indices.push(pi, pi + shft, pi + 1);
  33436. indices.push(pi + shft + 1, pi + 1, pi + shft);
  33437. pi += 1;
  33438. if (pi === min) {
  33439. p++;
  33440. if (p === lg.length - 1) {
  33441. shft = idx[0] - idx[p];
  33442. l1 = lg[p] - 1;
  33443. l2 = lg[0] - 1;
  33444. }
  33445. else {
  33446. shft = idx[p + 1] - idx[p];
  33447. l1 = lg[p] - 1;
  33448. l2 = lg[p + 1] - 1;
  33449. }
  33450. pi = idx[p];
  33451. min = (l1 < l2) ? l1 + pi : l2 + pi;
  33452. }
  33453. }
  33454. // normals
  33455. VertexData.ComputeNormals(positions, indices, normals);
  33456. if (closePath) {
  33457. var indexFirst = 0;
  33458. var indexLast = 0;
  33459. for (p = 0; p < pathArray.length; p++) {
  33460. indexFirst = idx[p] * 3;
  33461. if (p + 1 < pathArray.length) {
  33462. indexLast = (idx[p + 1] - 1) * 3;
  33463. }
  33464. else {
  33465. indexLast = normals.length - 3;
  33466. }
  33467. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  33468. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  33469. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33470. normals[indexLast] = normals[indexFirst];
  33471. normals[indexLast + 1] = normals[indexFirst + 1];
  33472. normals[indexLast + 2] = normals[indexFirst + 2];
  33473. }
  33474. }
  33475. // sides
  33476. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33477. // Colors
  33478. var colors = null;
  33479. if (customColors) {
  33480. colors = new Float32Array(customColors.length * 4);
  33481. for (var c = 0; c < customColors.length; c++) {
  33482. colors[c * 4] = customColors[c].r;
  33483. colors[c * 4 + 1] = customColors[c].g;
  33484. colors[c * 4 + 2] = customColors[c].b;
  33485. colors[c * 4 + 3] = customColors[c].a;
  33486. }
  33487. }
  33488. // Result
  33489. var vertexData = new VertexData();
  33490. var positions32 = new Float32Array(positions);
  33491. var normals32 = new Float32Array(normals);
  33492. var uvs32 = new Float32Array(uvs);
  33493. vertexData.indices = indices;
  33494. vertexData.positions = positions32;
  33495. vertexData.normals = normals32;
  33496. vertexData.uvs = uvs32;
  33497. if (colors) {
  33498. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  33499. }
  33500. if (closePath) {
  33501. vertexData._idx = idx;
  33502. }
  33503. return vertexData;
  33504. };
  33505. /**
  33506. * Creates the VertexData of the Box.
  33507. */
  33508. VertexData.CreateBox = function (options) {
  33509. var normalsSource = [
  33510. new BABYLON.Vector3(0, 0, 1),
  33511. new BABYLON.Vector3(0, 0, -1),
  33512. new BABYLON.Vector3(1, 0, 0),
  33513. new BABYLON.Vector3(-1, 0, 0),
  33514. new BABYLON.Vector3(0, 1, 0),
  33515. new BABYLON.Vector3(0, -1, 0)
  33516. ];
  33517. var indices = [];
  33518. var positions = [];
  33519. var normals = [];
  33520. var uvs = [];
  33521. var width = options.width || options.size || 1;
  33522. var height = options.height || options.size || 1;
  33523. var depth = options.depth || options.size || 1;
  33524. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33525. var faceUV = options.faceUV || new Array(6);
  33526. var faceColors = options.faceColors;
  33527. var colors = [];
  33528. // default face colors and UV if undefined
  33529. for (var f = 0; f < 6; f++) {
  33530. if (faceUV[f] === undefined) {
  33531. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33532. }
  33533. if (faceColors && faceColors[f] === undefined) {
  33534. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33535. }
  33536. }
  33537. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33538. // Create each face in turn.
  33539. for (var index = 0; index < normalsSource.length; index++) {
  33540. var normal = normalsSource[index];
  33541. // Get two vectors perpendicular to the face normal and to each other.
  33542. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33543. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33544. // Six indices (two triangles) per face.
  33545. var verticesLength = positions.length / 3;
  33546. indices.push(verticesLength);
  33547. indices.push(verticesLength + 1);
  33548. indices.push(verticesLength + 2);
  33549. indices.push(verticesLength);
  33550. indices.push(verticesLength + 2);
  33551. indices.push(verticesLength + 3);
  33552. // Four vertices per face.
  33553. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33554. positions.push(vertex.x, vertex.y, vertex.z);
  33555. normals.push(normal.x, normal.y, normal.z);
  33556. uvs.push(faceUV[index].z, faceUV[index].w);
  33557. if (faceColors) {
  33558. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33559. }
  33560. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33561. positions.push(vertex.x, vertex.y, vertex.z);
  33562. normals.push(normal.x, normal.y, normal.z);
  33563. uvs.push(faceUV[index].x, faceUV[index].w);
  33564. if (faceColors) {
  33565. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33566. }
  33567. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33568. positions.push(vertex.x, vertex.y, vertex.z);
  33569. normals.push(normal.x, normal.y, normal.z);
  33570. uvs.push(faceUV[index].x, faceUV[index].y);
  33571. if (faceColors) {
  33572. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33573. }
  33574. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33575. positions.push(vertex.x, vertex.y, vertex.z);
  33576. normals.push(normal.x, normal.y, normal.z);
  33577. uvs.push(faceUV[index].z, faceUV[index].y);
  33578. if (faceColors) {
  33579. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33580. }
  33581. }
  33582. // sides
  33583. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33584. // Result
  33585. var vertexData = new VertexData();
  33586. vertexData.indices = indices;
  33587. vertexData.positions = positions;
  33588. vertexData.normals = normals;
  33589. vertexData.uvs = uvs;
  33590. if (faceColors) {
  33591. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33592. vertexData.colors = totalColors;
  33593. }
  33594. return vertexData;
  33595. };
  33596. /**
  33597. * Creates the VertexData of the Sphere.
  33598. */
  33599. VertexData.CreateSphere = function (options) {
  33600. var segments = options.segments || 32;
  33601. var diameterX = options.diameterX || options.diameter || 1;
  33602. var diameterY = options.diameterY || options.diameter || 1;
  33603. var diameterZ = options.diameterZ || options.diameter || 1;
  33604. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33605. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33606. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33607. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33608. var totalZRotationSteps = 2 + segments;
  33609. var totalYRotationSteps = 2 * totalZRotationSteps;
  33610. var indices = [];
  33611. var positions = [];
  33612. var normals = [];
  33613. var uvs = [];
  33614. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33615. var normalizedZ = zRotationStep / totalZRotationSteps;
  33616. var angleZ = normalizedZ * Math.PI * slice;
  33617. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33618. var normalizedY = yRotationStep / totalYRotationSteps;
  33619. var angleY = normalizedY * Math.PI * 2 * arc;
  33620. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33621. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33622. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33623. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33624. var vertex = complete.multiply(radius);
  33625. var normal = complete.divide(radius).normalize();
  33626. positions.push(vertex.x, vertex.y, vertex.z);
  33627. normals.push(normal.x, normal.y, normal.z);
  33628. uvs.push(normalizedY, normalizedZ);
  33629. }
  33630. if (zRotationStep > 0) {
  33631. var verticesCount = positions.length / 3;
  33632. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33633. indices.push((firstIndex));
  33634. indices.push((firstIndex + 1));
  33635. indices.push(firstIndex + totalYRotationSteps + 1);
  33636. indices.push((firstIndex + totalYRotationSteps + 1));
  33637. indices.push((firstIndex + 1));
  33638. indices.push((firstIndex + totalYRotationSteps + 2));
  33639. }
  33640. }
  33641. }
  33642. // Sides
  33643. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33644. // Result
  33645. var vertexData = new VertexData();
  33646. vertexData.indices = indices;
  33647. vertexData.positions = positions;
  33648. vertexData.normals = normals;
  33649. vertexData.uvs = uvs;
  33650. return vertexData;
  33651. };
  33652. /**
  33653. * Creates the VertexData of the Cylinder or Cone.
  33654. */
  33655. VertexData.CreateCylinder = function (options) {
  33656. var height = options.height || 2;
  33657. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33658. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33659. var tessellation = options.tessellation || 24;
  33660. var subdivisions = options.subdivisions || 1;
  33661. var hasRings = options.hasRings ? true : false;
  33662. var enclose = options.enclose ? true : false;
  33663. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33664. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33665. var faceUV = options.faceUV || new Array(3);
  33666. var faceColors = options.faceColors;
  33667. // default face colors and UV if undefined
  33668. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33669. var ringNb = (hasRings) ? subdivisions : 1;
  33670. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33671. var f;
  33672. for (f = 0; f < surfaceNb; f++) {
  33673. if (faceColors && faceColors[f] === undefined) {
  33674. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33675. }
  33676. }
  33677. for (f = 0; f < surfaceNb; f++) {
  33678. if (faceUV && faceUV[f] === undefined) {
  33679. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33680. }
  33681. }
  33682. var indices = new Array();
  33683. var positions = new Array();
  33684. var normals = new Array();
  33685. var uvs = new Array();
  33686. var colors = new Array();
  33687. var angle_step = Math.PI * 2 * arc / tessellation;
  33688. var angle;
  33689. var h;
  33690. var radius;
  33691. var tan = (diameterBottom - diameterTop) / 2 / height;
  33692. var ringVertex = BABYLON.Vector3.Zero();
  33693. var ringNormal = BABYLON.Vector3.Zero();
  33694. var ringFirstVertex = BABYLON.Vector3.Zero();
  33695. var ringFirstNormal = BABYLON.Vector3.Zero();
  33696. var quadNormal = BABYLON.Vector3.Zero();
  33697. var Y = BABYLON.Axis.Y;
  33698. // positions, normals, uvs
  33699. var i;
  33700. var j;
  33701. var r;
  33702. var ringIdx = 1;
  33703. var s = 1; // surface index
  33704. var cs = 0;
  33705. var v = 0;
  33706. for (i = 0; i <= subdivisions; i++) {
  33707. h = i / subdivisions;
  33708. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33709. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33710. for (r = 0; r < ringIdx; r++) {
  33711. if (hasRings) {
  33712. s += r;
  33713. }
  33714. if (enclose) {
  33715. s += 2 * r;
  33716. }
  33717. for (j = 0; j <= tessellation; j++) {
  33718. angle = j * angle_step;
  33719. // position
  33720. ringVertex.x = Math.cos(-angle) * radius;
  33721. ringVertex.y = -height / 2 + h * height;
  33722. ringVertex.z = Math.sin(-angle) * radius;
  33723. // normal
  33724. if (diameterTop === 0 && i === subdivisions) {
  33725. // if no top cap, reuse former normals
  33726. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33727. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33728. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33729. }
  33730. else {
  33731. ringNormal.x = ringVertex.x;
  33732. ringNormal.z = ringVertex.z;
  33733. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33734. ringNormal.normalize();
  33735. }
  33736. // keep first ring vertex values for enclose
  33737. if (j === 0) {
  33738. ringFirstVertex.copyFrom(ringVertex);
  33739. ringFirstNormal.copyFrom(ringNormal);
  33740. }
  33741. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33742. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33743. if (hasRings) {
  33744. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33745. }
  33746. else {
  33747. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33748. }
  33749. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33750. if (faceColors) {
  33751. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33752. }
  33753. }
  33754. // if enclose, add four vertices and their dedicated normals
  33755. if (arc !== 1 && enclose) {
  33756. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33757. positions.push(0, ringVertex.y, 0);
  33758. positions.push(0, ringVertex.y, 0);
  33759. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33760. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33761. quadNormal.normalize();
  33762. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33763. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33764. quadNormal.normalize();
  33765. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33766. if (hasRings) {
  33767. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33768. }
  33769. else {
  33770. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33771. }
  33772. uvs.push(faceUV[s + 1].x, v);
  33773. uvs.push(faceUV[s + 1].z, v);
  33774. if (hasRings) {
  33775. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33776. }
  33777. else {
  33778. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33779. }
  33780. uvs.push(faceUV[s + 2].x, v);
  33781. uvs.push(faceUV[s + 2].z, v);
  33782. if (faceColors) {
  33783. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33784. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33785. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33786. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33787. }
  33788. }
  33789. if (cs !== s) {
  33790. cs = s;
  33791. }
  33792. }
  33793. }
  33794. // indices
  33795. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33796. var s;
  33797. i = 0;
  33798. for (s = 0; s < subdivisions; s++) {
  33799. var i0 = 0;
  33800. var i1 = 0;
  33801. var i2 = 0;
  33802. var i3 = 0;
  33803. for (j = 0; j < tessellation; j++) {
  33804. i0 = i * (e + 1) + j;
  33805. i1 = (i + 1) * (e + 1) + j;
  33806. i2 = i * (e + 1) + (j + 1);
  33807. i3 = (i + 1) * (e + 1) + (j + 1);
  33808. indices.push(i0, i1, i2);
  33809. indices.push(i3, i2, i1);
  33810. }
  33811. if (arc !== 1 && enclose) {
  33812. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33813. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33814. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33815. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33816. }
  33817. i = (hasRings) ? (i + 2) : (i + 1);
  33818. }
  33819. // Caps
  33820. var createCylinderCap = function (isTop) {
  33821. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33822. if (radius === 0) {
  33823. return;
  33824. }
  33825. // Cap positions, normals & uvs
  33826. var angle;
  33827. var circleVector;
  33828. var i;
  33829. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33830. var c = null;
  33831. if (faceColors) {
  33832. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33833. }
  33834. // cap center
  33835. var vbase = positions.length / 3;
  33836. var offset = isTop ? height / 2 : -height / 2;
  33837. var center = new BABYLON.Vector3(0, offset, 0);
  33838. positions.push(center.x, center.y, center.z);
  33839. normals.push(0, isTop ? 1 : -1, 0);
  33840. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33841. if (c) {
  33842. colors.push(c.r, c.g, c.b, c.a);
  33843. }
  33844. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33845. for (i = 0; i <= tessellation; i++) {
  33846. angle = Math.PI * 2 * i * arc / tessellation;
  33847. var cos = Math.cos(-angle);
  33848. var sin = Math.sin(-angle);
  33849. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33850. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33851. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33852. normals.push(0, isTop ? 1 : -1, 0);
  33853. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33854. if (c) {
  33855. colors.push(c.r, c.g, c.b, c.a);
  33856. }
  33857. }
  33858. // Cap indices
  33859. for (i = 0; i < tessellation; i++) {
  33860. if (!isTop) {
  33861. indices.push(vbase);
  33862. indices.push(vbase + (i + 1));
  33863. indices.push(vbase + (i + 2));
  33864. }
  33865. else {
  33866. indices.push(vbase);
  33867. indices.push(vbase + (i + 2));
  33868. indices.push(vbase + (i + 1));
  33869. }
  33870. }
  33871. };
  33872. // add caps to geometry
  33873. createCylinderCap(false);
  33874. createCylinderCap(true);
  33875. // Sides
  33876. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33877. var vertexData = new VertexData();
  33878. vertexData.indices = indices;
  33879. vertexData.positions = positions;
  33880. vertexData.normals = normals;
  33881. vertexData.uvs = uvs;
  33882. if (faceColors) {
  33883. vertexData.colors = colors;
  33884. }
  33885. return vertexData;
  33886. };
  33887. /**
  33888. * Creates the VertexData of the Torus.
  33889. */
  33890. VertexData.CreateTorus = function (options) {
  33891. var indices = [];
  33892. var positions = [];
  33893. var normals = [];
  33894. var uvs = [];
  33895. var diameter = options.diameter || 1;
  33896. var thickness = options.thickness || 0.5;
  33897. var tessellation = options.tessellation || 16;
  33898. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33899. var stride = tessellation + 1;
  33900. for (var i = 0; i <= tessellation; i++) {
  33901. var u = i / tessellation;
  33902. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33903. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33904. for (var j = 0; j <= tessellation; j++) {
  33905. var v = 1 - j / tessellation;
  33906. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33907. var dx = Math.cos(innerAngle);
  33908. var dy = Math.sin(innerAngle);
  33909. // Create a vertex.
  33910. var normal = new BABYLON.Vector3(dx, dy, 0);
  33911. var position = normal.scale(thickness / 2);
  33912. var textureCoordinate = new BABYLON.Vector2(u, v);
  33913. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33914. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33915. positions.push(position.x, position.y, position.z);
  33916. normals.push(normal.x, normal.y, normal.z);
  33917. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33918. // And create indices for two triangles.
  33919. var nextI = (i + 1) % stride;
  33920. var nextJ = (j + 1) % stride;
  33921. indices.push(i * stride + j);
  33922. indices.push(i * stride + nextJ);
  33923. indices.push(nextI * stride + j);
  33924. indices.push(i * stride + nextJ);
  33925. indices.push(nextI * stride + nextJ);
  33926. indices.push(nextI * stride + j);
  33927. }
  33928. }
  33929. // Sides
  33930. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33931. // Result
  33932. var vertexData = new VertexData();
  33933. vertexData.indices = indices;
  33934. vertexData.positions = positions;
  33935. vertexData.normals = normals;
  33936. vertexData.uvs = uvs;
  33937. return vertexData;
  33938. };
  33939. /**
  33940. * Creates the VertexData of the LineSystem.
  33941. */
  33942. VertexData.CreateLineSystem = function (options) {
  33943. var indices = [];
  33944. var positions = [];
  33945. var lines = options.lines;
  33946. var colors = options.colors;
  33947. var vertexColors = [];
  33948. var idx = 0;
  33949. for (var l = 0; l < lines.length; l++) {
  33950. var points = lines[l];
  33951. for (var index = 0; index < points.length; index++) {
  33952. positions.push(points[index].x, points[index].y, points[index].z);
  33953. if (colors) {
  33954. var color = colors[l];
  33955. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33956. }
  33957. if (index > 0) {
  33958. indices.push(idx - 1);
  33959. indices.push(idx);
  33960. }
  33961. idx++;
  33962. }
  33963. }
  33964. var vertexData = new VertexData();
  33965. vertexData.indices = indices;
  33966. vertexData.positions = positions;
  33967. if (colors) {
  33968. vertexData.colors = vertexColors;
  33969. }
  33970. return vertexData;
  33971. };
  33972. /**
  33973. * Create the VertexData of the DashedLines.
  33974. */
  33975. VertexData.CreateDashedLines = function (options) {
  33976. var dashSize = options.dashSize || 3;
  33977. var gapSize = options.gapSize || 1;
  33978. var dashNb = options.dashNb || 200;
  33979. var points = options.points;
  33980. var positions = new Array();
  33981. var indices = new Array();
  33982. var curvect = BABYLON.Vector3.Zero();
  33983. var lg = 0;
  33984. var nb = 0;
  33985. var shft = 0;
  33986. var dashshft = 0;
  33987. var curshft = 0;
  33988. var idx = 0;
  33989. var i = 0;
  33990. for (i = 0; i < points.length - 1; i++) {
  33991. points[i + 1].subtractToRef(points[i], curvect);
  33992. lg += curvect.length();
  33993. }
  33994. shft = lg / dashNb;
  33995. dashshft = dashSize * shft / (dashSize + gapSize);
  33996. for (i = 0; i < points.length - 1; i++) {
  33997. points[i + 1].subtractToRef(points[i], curvect);
  33998. nb = Math.floor(curvect.length() / shft);
  33999. curvect.normalize();
  34000. for (var j = 0; j < nb; j++) {
  34001. curshft = shft * j;
  34002. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  34003. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  34004. indices.push(idx, idx + 1);
  34005. idx += 2;
  34006. }
  34007. }
  34008. // Result
  34009. var vertexData = new VertexData();
  34010. vertexData.positions = positions;
  34011. vertexData.indices = indices;
  34012. return vertexData;
  34013. };
  34014. /**
  34015. * Creates the VertexData of the Ground.
  34016. */
  34017. VertexData.CreateGround = function (options) {
  34018. var indices = [];
  34019. var positions = [];
  34020. var normals = [];
  34021. var uvs = [];
  34022. var row, col;
  34023. var width = options.width || 1;
  34024. var height = options.height || 1;
  34025. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  34026. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  34027. for (row = 0; row <= subdivisionsY; row++) {
  34028. for (col = 0; col <= subdivisionsX; col++) {
  34029. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  34030. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34031. positions.push(position.x, position.y, position.z);
  34032. normals.push(normal.x, normal.y, normal.z);
  34033. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  34034. }
  34035. }
  34036. for (row = 0; row < subdivisionsY; row++) {
  34037. for (col = 0; col < subdivisionsX; col++) {
  34038. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34039. indices.push(col + 1 + row * (subdivisionsX + 1));
  34040. indices.push(col + row * (subdivisionsX + 1));
  34041. indices.push(col + (row + 1) * (subdivisionsX + 1));
  34042. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34043. indices.push(col + row * (subdivisionsX + 1));
  34044. }
  34045. }
  34046. // Result
  34047. var vertexData = new VertexData();
  34048. vertexData.indices = indices;
  34049. vertexData.positions = positions;
  34050. vertexData.normals = normals;
  34051. vertexData.uvs = uvs;
  34052. return vertexData;
  34053. };
  34054. /**
  34055. * Creates the VertexData of the TiledGround.
  34056. */
  34057. VertexData.CreateTiledGround = function (options) {
  34058. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  34059. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  34060. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  34061. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  34062. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  34063. var precision = options.precision || { w: 1, h: 1 };
  34064. var indices = new Array();
  34065. var positions = new Array();
  34066. var normals = new Array();
  34067. var uvs = new Array();
  34068. var row, col, tileRow, tileCol;
  34069. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  34070. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  34071. precision.w = (precision.w < 1) ? 1 : precision.w;
  34072. precision.h = (precision.h < 1) ? 1 : precision.h;
  34073. var tileSize = {
  34074. 'w': (xmax - xmin) / subdivisions.w,
  34075. 'h': (zmax - zmin) / subdivisions.h
  34076. };
  34077. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  34078. // Indices
  34079. var base = positions.length / 3;
  34080. var rowLength = precision.w + 1;
  34081. for (row = 0; row < precision.h; row++) {
  34082. for (col = 0; col < precision.w; col++) {
  34083. var square = [
  34084. base + col + row * rowLength,
  34085. base + (col + 1) + row * rowLength,
  34086. base + (col + 1) + (row + 1) * rowLength,
  34087. base + col + (row + 1) * rowLength
  34088. ];
  34089. indices.push(square[1]);
  34090. indices.push(square[2]);
  34091. indices.push(square[3]);
  34092. indices.push(square[0]);
  34093. indices.push(square[1]);
  34094. indices.push(square[3]);
  34095. }
  34096. }
  34097. // Position, normals and uvs
  34098. var position = BABYLON.Vector3.Zero();
  34099. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34100. for (row = 0; row <= precision.h; row++) {
  34101. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  34102. for (col = 0; col <= precision.w; col++) {
  34103. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  34104. position.y = 0;
  34105. positions.push(position.x, position.y, position.z);
  34106. normals.push(normal.x, normal.y, normal.z);
  34107. uvs.push(col / precision.w, row / precision.h);
  34108. }
  34109. }
  34110. }
  34111. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  34112. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  34113. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  34114. }
  34115. }
  34116. // Result
  34117. var vertexData = new VertexData();
  34118. vertexData.indices = indices;
  34119. vertexData.positions = positions;
  34120. vertexData.normals = normals;
  34121. vertexData.uvs = uvs;
  34122. return vertexData;
  34123. };
  34124. /**
  34125. * Creates the VertexData of the Ground designed from a heightmap.
  34126. */
  34127. VertexData.CreateGroundFromHeightMap = function (options) {
  34128. var indices = [];
  34129. var positions = [];
  34130. var normals = [];
  34131. var uvs = [];
  34132. var row, col;
  34133. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  34134. // Vertices
  34135. for (row = 0; row <= options.subdivisions; row++) {
  34136. for (col = 0; col <= options.subdivisions; col++) {
  34137. 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));
  34138. // Compute height
  34139. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  34140. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  34141. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  34142. var r = options.buffer[pos] / 255.0;
  34143. var g = options.buffer[pos + 1] / 255.0;
  34144. var b = options.buffer[pos + 2] / 255.0;
  34145. var gradient = r * filter.r + g * filter.g + b * filter.b;
  34146. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  34147. // Add vertex
  34148. positions.push(position.x, position.y, position.z);
  34149. normals.push(0, 0, 0);
  34150. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  34151. }
  34152. }
  34153. // Indices
  34154. for (row = 0; row < options.subdivisions; row++) {
  34155. for (col = 0; col < options.subdivisions; col++) {
  34156. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34157. indices.push(col + 1 + row * (options.subdivisions + 1));
  34158. indices.push(col + row * (options.subdivisions + 1));
  34159. indices.push(col + (row + 1) * (options.subdivisions + 1));
  34160. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34161. indices.push(col + row * (options.subdivisions + 1));
  34162. }
  34163. }
  34164. // Normals
  34165. VertexData.ComputeNormals(positions, indices, normals);
  34166. // Result
  34167. var vertexData = new VertexData();
  34168. vertexData.indices = indices;
  34169. vertexData.positions = positions;
  34170. vertexData.normals = normals;
  34171. vertexData.uvs = uvs;
  34172. return vertexData;
  34173. };
  34174. /**
  34175. * Creates the VertexData of the Plane.
  34176. */
  34177. VertexData.CreatePlane = function (options) {
  34178. var indices = [];
  34179. var positions = [];
  34180. var normals = [];
  34181. var uvs = [];
  34182. var width = options.width || options.size || 1;
  34183. var height = options.height || options.size || 1;
  34184. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34185. // Vertices
  34186. var halfWidth = width / 2.0;
  34187. var halfHeight = height / 2.0;
  34188. positions.push(-halfWidth, -halfHeight, 0);
  34189. normals.push(0, 0, -1.0);
  34190. uvs.push(0.0, 0.0);
  34191. positions.push(halfWidth, -halfHeight, 0);
  34192. normals.push(0, 0, -1.0);
  34193. uvs.push(1.0, 0.0);
  34194. positions.push(halfWidth, halfHeight, 0);
  34195. normals.push(0, 0, -1.0);
  34196. uvs.push(1.0, 1.0);
  34197. positions.push(-halfWidth, halfHeight, 0);
  34198. normals.push(0, 0, -1.0);
  34199. uvs.push(0.0, 1.0);
  34200. // Indices
  34201. indices.push(0);
  34202. indices.push(1);
  34203. indices.push(2);
  34204. indices.push(0);
  34205. indices.push(2);
  34206. indices.push(3);
  34207. // Sides
  34208. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34209. // Result
  34210. var vertexData = new VertexData();
  34211. vertexData.indices = indices;
  34212. vertexData.positions = positions;
  34213. vertexData.normals = normals;
  34214. vertexData.uvs = uvs;
  34215. return vertexData;
  34216. };
  34217. /**
  34218. * Creates the VertexData of the Disc or regular Polygon.
  34219. */
  34220. VertexData.CreateDisc = function (options) {
  34221. var positions = new Array();
  34222. var indices = new Array();
  34223. var normals = new Array();
  34224. var uvs = new Array();
  34225. var radius = options.radius || 0.5;
  34226. var tessellation = options.tessellation || 64;
  34227. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  34228. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34229. // positions and uvs
  34230. positions.push(0, 0, 0); // disc center first
  34231. uvs.push(0.5, 0.5);
  34232. var theta = Math.PI * 2 * arc;
  34233. var step = theta / tessellation;
  34234. for (var a = 0; a < theta; a += step) {
  34235. var x = Math.cos(a);
  34236. var y = Math.sin(a);
  34237. var u = (x + 1) / 2;
  34238. var v = (1 - y) / 2;
  34239. positions.push(radius * x, radius * y, 0);
  34240. uvs.push(u, v);
  34241. }
  34242. if (arc === 1) {
  34243. positions.push(positions[3], positions[4], positions[5]); // close the circle
  34244. uvs.push(uvs[2], uvs[3]);
  34245. }
  34246. //indices
  34247. var vertexNb = positions.length / 3;
  34248. for (var i = 1; i < vertexNb - 1; i++) {
  34249. indices.push(i + 1, 0, i);
  34250. }
  34251. // result
  34252. VertexData.ComputeNormals(positions, indices, normals);
  34253. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34254. var vertexData = new VertexData();
  34255. vertexData.indices = indices;
  34256. vertexData.positions = positions;
  34257. vertexData.normals = normals;
  34258. vertexData.uvs = uvs;
  34259. return vertexData;
  34260. };
  34261. /**
  34262. * Re-creates the VertexData of the Polygon for sideOrientation.
  34263. */
  34264. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  34265. var faceUV = fUV || new Array(3);
  34266. var faceColors = fColors;
  34267. var colors = [];
  34268. // default face colors and UV if undefined
  34269. for (var f = 0; f < 3; f++) {
  34270. if (faceUV[f] === undefined) {
  34271. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34272. }
  34273. if (faceColors && faceColors[f] === undefined) {
  34274. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34275. }
  34276. }
  34277. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34278. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34279. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34280. var indices = polygon.getIndices();
  34281. // set face colours and textures
  34282. var idx = 0;
  34283. var face = 0;
  34284. for (var index = 0; index < normals.length; index += 3) {
  34285. //Edge Face no. 1
  34286. if (Math.abs(normals[index + 1]) < 0.001) {
  34287. face = 1;
  34288. }
  34289. //Top Face no. 0
  34290. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  34291. face = 0;
  34292. }
  34293. //Bottom Face no. 2
  34294. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  34295. face = 2;
  34296. }
  34297. idx = index / 3;
  34298. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  34299. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  34300. if (faceColors) {
  34301. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  34302. }
  34303. }
  34304. // sides
  34305. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  34306. // Result
  34307. var vertexData = new VertexData();
  34308. vertexData.indices = indices;
  34309. vertexData.positions = positions;
  34310. vertexData.normals = normals;
  34311. vertexData.uvs = uvs;
  34312. if (faceColors) {
  34313. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  34314. vertexData.colors = totalColors;
  34315. }
  34316. return vertexData;
  34317. };
  34318. /**
  34319. * Creates the VertexData of the IcoSphere.
  34320. */
  34321. VertexData.CreateIcoSphere = function (options) {
  34322. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34323. var radius = options.radius || 1;
  34324. var flat = (options.flat === undefined) ? true : options.flat;
  34325. var subdivisions = options.subdivisions || 4;
  34326. var radiusX = options.radiusX || radius;
  34327. var radiusY = options.radiusY || radius;
  34328. var radiusZ = options.radiusZ || radius;
  34329. var t = (1 + Math.sqrt(5)) / 2;
  34330. // 12 vertex x,y,z
  34331. var ico_vertices = [
  34332. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  34333. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  34334. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  34335. ];
  34336. // index of 3 vertex makes a face of icopshere
  34337. var ico_indices = [
  34338. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  34339. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  34340. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  34341. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  34342. ];
  34343. // vertex for uv have aliased position, not for UV
  34344. var vertices_unalias_id = [
  34345. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  34346. // vertex alias
  34347. 0,
  34348. 2,
  34349. 3,
  34350. 3,
  34351. 3,
  34352. 4,
  34353. 7,
  34354. 8,
  34355. 9,
  34356. 9,
  34357. 10,
  34358. 11 // 23: B + 12
  34359. ];
  34360. // uv as integer step (not pixels !)
  34361. var ico_vertexuv = [
  34362. 5, 1, 3, 1, 6, 4, 0, 0,
  34363. 5, 3, 4, 2, 2, 2, 4, 0,
  34364. 2, 0, 1, 1, 6, 0, 6, 2,
  34365. // vertex alias (for same vertex on different faces)
  34366. 0, 4,
  34367. 3, 3,
  34368. 4, 4,
  34369. 3, 1,
  34370. 4, 2,
  34371. 4, 4,
  34372. 0, 2,
  34373. 1, 1,
  34374. 2, 2,
  34375. 3, 3,
  34376. 1, 3,
  34377. 2, 4 // 23: B + 12
  34378. ];
  34379. // Vertices[0, 1, ...9, A, B] : position on UV plane
  34380. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  34381. // First island of uv mapping
  34382. // v = 4h 3+ 2
  34383. // v = 3h 9+ 4
  34384. // v = 2h 9+ 5 B
  34385. // v = 1h 9 1 0
  34386. // v = 0h 3 8 7 A
  34387. // u = 0 1 2 3 4 5 6 *a
  34388. // Second island of uv mapping
  34389. // v = 4h 0+ B+ 4+
  34390. // v = 3h A+ 2+
  34391. // v = 2h 7+ 6 3+
  34392. // v = 1h 8+ 3+
  34393. // v = 0h
  34394. // u = 0 1 2 3 4 5 6 *a
  34395. // Face layout on texture UV mapping
  34396. // ============
  34397. // \ 4 /\ 16 / ======
  34398. // \ / \ / /\ 11 /
  34399. // \/ 7 \/ / \ /
  34400. // ======= / 10 \/
  34401. // /\ 17 /\ =======
  34402. // / \ / \ \ 15 /\
  34403. // / 8 \/ 12 \ \ / \
  34404. // ============ \/ 6 \
  34405. // \ 18 /\ ============
  34406. // \ / \ \ 5 /\ 0 /
  34407. // \/ 13 \ \ / \ /
  34408. // ======= \/ 1 \/
  34409. // =============
  34410. // /\ 19 /\ 2 /\
  34411. // / \ / \ / \
  34412. // / 14 \/ 9 \/ 3 \
  34413. // ===================
  34414. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  34415. var ustep = 138 / 1024;
  34416. var vstep = 239 / 1024;
  34417. var uoffset = 60 / 1024;
  34418. var voffset = 26 / 1024;
  34419. // Second island should have margin, not to touch the first island
  34420. // avoid any borderline artefact in pixel rounding
  34421. var island_u_offset = -40 / 1024;
  34422. var island_v_offset = +20 / 1024;
  34423. // face is either island 0 or 1 :
  34424. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  34425. var island = [
  34426. 0, 0, 0, 0, 1,
  34427. 0, 0, 1, 1, 0,
  34428. 0, 0, 1, 1, 0,
  34429. 0, 1, 1, 1, 0 // 15 - 19
  34430. ];
  34431. var indices = new Array();
  34432. var positions = new Array();
  34433. var normals = new Array();
  34434. var uvs = new Array();
  34435. var current_indice = 0;
  34436. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  34437. var face_vertex_pos = new Array(3);
  34438. var face_vertex_uv = new Array(3);
  34439. var v012;
  34440. for (v012 = 0; v012 < 3; v012++) {
  34441. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  34442. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  34443. }
  34444. // create all with normals
  34445. for (var face = 0; face < 20; face++) {
  34446. // 3 vertex per face
  34447. for (v012 = 0; v012 < 3; v012++) {
  34448. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  34449. var v_id = ico_indices[3 * face + v012];
  34450. // vertex have 3D position (x,y,z)
  34451. 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]);
  34452. // Normalize to get normal, then scale to radius
  34453. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  34454. // uv Coordinates from vertex ID
  34455. 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);
  34456. }
  34457. // Subdivide the face (interpolate pos, norm, uv)
  34458. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  34459. // - norm is linear interpolation of vertex corner normal
  34460. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  34461. // - uv is linear interpolation
  34462. //
  34463. // Topology is as below for sub-divide by 2
  34464. // vertex shown as v0,v1,v2
  34465. // interp index is i1 to progress in range [v0,v1[
  34466. // interp index is i2 to progress in range [v0,v2[
  34467. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  34468. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34469. //
  34470. //
  34471. // i2 v2
  34472. // ^ ^
  34473. // / / \
  34474. // / / \
  34475. // / / \
  34476. // / / (0,1) \
  34477. // / #---------\
  34478. // / / \ (0,0)'/ \
  34479. // / / \ / \
  34480. // / / \ / \
  34481. // / / (0,0) \ / (1,0) \
  34482. // / #---------#---------\
  34483. // v0 v1
  34484. //
  34485. // --------------------> i1
  34486. //
  34487. // interp of (i1,i2):
  34488. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34489. // along i1 : lerp(x0,x1, i1/(S-i2))
  34490. //
  34491. // centroid of triangle is needed to get help normal computation
  34492. // (c1,c2) are used for centroid location
  34493. var interp_vertex = function (i1, i2, c1, c2) {
  34494. // vertex is interpolated from
  34495. // - face_vertex_pos[0..2]
  34496. // - face_vertex_uv[0..2]
  34497. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34498. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34499. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34500. pos_interp.normalize();
  34501. var vertex_normal;
  34502. if (flat) {
  34503. // in flat mode, recalculate normal as face centroid normal
  34504. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34505. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34506. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34507. }
  34508. else {
  34509. // in smooth mode, recalculate normal from each single vertex position
  34510. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34511. }
  34512. // Vertex normal need correction due to X,Y,Z radius scaling
  34513. vertex_normal.x /= radiusX;
  34514. vertex_normal.y /= radiusY;
  34515. vertex_normal.z /= radiusZ;
  34516. vertex_normal.normalize();
  34517. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34518. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34519. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34520. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34521. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34522. uvs.push(uv_interp.x, uv_interp.y);
  34523. // push each vertex has member of a face
  34524. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34525. indices.push(current_indice);
  34526. current_indice++;
  34527. };
  34528. for (var i2 = 0; i2 < subdivisions; i2++) {
  34529. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34530. // face : (i1,i2) for /\ :
  34531. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34532. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34533. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34534. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34535. if (i1 + i2 + 1 < subdivisions) {
  34536. // face : (i1,i2)' for \/ :
  34537. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34538. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34539. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34540. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34541. }
  34542. }
  34543. }
  34544. }
  34545. // Sides
  34546. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34547. // Result
  34548. var vertexData = new VertexData();
  34549. vertexData.indices = indices;
  34550. vertexData.positions = positions;
  34551. vertexData.normals = normals;
  34552. vertexData.uvs = uvs;
  34553. return vertexData;
  34554. };
  34555. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34556. /**
  34557. * Creates the VertexData of the Polyhedron.
  34558. */
  34559. VertexData.CreatePolyhedron = function (options) {
  34560. // provided polyhedron types :
  34561. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34562. // 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)
  34563. var polyhedra = [];
  34564. 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]] };
  34565. 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]] };
  34566. polyhedra[2] = {
  34567. 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]],
  34568. 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]]
  34569. };
  34570. polyhedra[3] = {
  34571. 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]],
  34572. 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]]
  34573. };
  34574. polyhedra[4] = {
  34575. 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]],
  34576. 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]]
  34577. };
  34578. 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]] };
  34579. 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]] };
  34580. 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]] };
  34581. 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]] };
  34582. 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]] };
  34583. 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]] };
  34584. 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]] };
  34585. 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]] };
  34586. 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]] };
  34587. polyhedra[14] = {
  34588. 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]],
  34589. 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]]
  34590. };
  34591. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34592. var size = options.size;
  34593. var sizeX = options.sizeX || size || 1;
  34594. var sizeY = options.sizeY || size || 1;
  34595. var sizeZ = options.sizeZ || size || 1;
  34596. var data = options.custom || polyhedra[type];
  34597. var nbfaces = data.face.length;
  34598. var faceUV = options.faceUV || new Array(nbfaces);
  34599. var faceColors = options.faceColors;
  34600. var flat = (options.flat === undefined) ? true : options.flat;
  34601. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34602. var positions = new Array();
  34603. var indices = new Array();
  34604. var normals = new Array();
  34605. var uvs = new Array();
  34606. var colors = new Array();
  34607. var index = 0;
  34608. var faceIdx = 0; // face cursor in the array "indexes"
  34609. var indexes = new Array();
  34610. var i = 0;
  34611. var f = 0;
  34612. var u, v, ang, x, y, tmp;
  34613. // default face colors and UV if undefined
  34614. if (flat) {
  34615. for (f = 0; f < nbfaces; f++) {
  34616. if (faceColors && faceColors[f] === undefined) {
  34617. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34618. }
  34619. if (faceUV && faceUV[f] === undefined) {
  34620. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34621. }
  34622. }
  34623. }
  34624. if (!flat) {
  34625. for (i = 0; i < data.vertex.length; i++) {
  34626. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34627. uvs.push(0, 0);
  34628. }
  34629. for (f = 0; f < nbfaces; f++) {
  34630. for (i = 0; i < data.face[f].length - 2; i++) {
  34631. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34632. }
  34633. }
  34634. }
  34635. else {
  34636. for (f = 0; f < nbfaces; f++) {
  34637. var fl = data.face[f].length; // number of vertices of the current face
  34638. ang = 2 * Math.PI / fl;
  34639. x = 0.5 * Math.tan(ang / 2);
  34640. y = 0.5;
  34641. // positions, uvs, colors
  34642. for (i = 0; i < fl; i++) {
  34643. // positions
  34644. 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);
  34645. indexes.push(index);
  34646. index++;
  34647. // uvs
  34648. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34649. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34650. uvs.push(u, v);
  34651. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34652. y = x * Math.sin(ang) + y * Math.cos(ang);
  34653. x = tmp;
  34654. // colors
  34655. if (faceColors) {
  34656. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34657. }
  34658. }
  34659. // indices from indexes
  34660. for (i = 0; i < fl - 2; i++) {
  34661. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34662. }
  34663. faceIdx += fl;
  34664. }
  34665. }
  34666. VertexData.ComputeNormals(positions, indices, normals);
  34667. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34668. var vertexData = new VertexData();
  34669. vertexData.positions = positions;
  34670. vertexData.indices = indices;
  34671. vertexData.normals = normals;
  34672. vertexData.uvs = uvs;
  34673. if (faceColors && flat) {
  34674. vertexData.colors = colors;
  34675. }
  34676. return vertexData;
  34677. };
  34678. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34679. /**
  34680. * Creates the VertexData of the Torus Knot.
  34681. */
  34682. VertexData.CreateTorusKnot = function (options) {
  34683. var indices = new Array();
  34684. var positions = new Array();
  34685. var normals = new Array();
  34686. var uvs = new Array();
  34687. var radius = options.radius || 2;
  34688. var tube = options.tube || 0.5;
  34689. var radialSegments = options.radialSegments || 32;
  34690. var tubularSegments = options.tubularSegments || 32;
  34691. var p = options.p || 2;
  34692. var q = options.q || 3;
  34693. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34694. // Helper
  34695. var getPos = function (angle) {
  34696. var cu = Math.cos(angle);
  34697. var su = Math.sin(angle);
  34698. var quOverP = q / p * angle;
  34699. var cs = Math.cos(quOverP);
  34700. var tx = radius * (2 + cs) * 0.5 * cu;
  34701. var ty = radius * (2 + cs) * su * 0.5;
  34702. var tz = radius * Math.sin(quOverP) * 0.5;
  34703. return new BABYLON.Vector3(tx, ty, tz);
  34704. };
  34705. // Vertices
  34706. var i;
  34707. var j;
  34708. for (i = 0; i <= radialSegments; i++) {
  34709. var modI = i % radialSegments;
  34710. var u = modI / radialSegments * 2 * p * Math.PI;
  34711. var p1 = getPos(u);
  34712. var p2 = getPos(u + 0.01);
  34713. var tang = p2.subtract(p1);
  34714. var n = p2.add(p1);
  34715. var bitan = BABYLON.Vector3.Cross(tang, n);
  34716. n = BABYLON.Vector3.Cross(bitan, tang);
  34717. bitan.normalize();
  34718. n.normalize();
  34719. for (j = 0; j < tubularSegments; j++) {
  34720. var modJ = j % tubularSegments;
  34721. var v = modJ / tubularSegments * 2 * Math.PI;
  34722. var cx = -tube * Math.cos(v);
  34723. var cy = tube * Math.sin(v);
  34724. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34725. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34726. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34727. uvs.push(i / radialSegments);
  34728. uvs.push(j / tubularSegments);
  34729. }
  34730. }
  34731. for (i = 0; i < radialSegments; i++) {
  34732. for (j = 0; j < tubularSegments; j++) {
  34733. var jNext = (j + 1) % tubularSegments;
  34734. var a = i * tubularSegments + j;
  34735. var b = (i + 1) * tubularSegments + j;
  34736. var c = (i + 1) * tubularSegments + jNext;
  34737. var d = i * tubularSegments + jNext;
  34738. indices.push(d);
  34739. indices.push(b);
  34740. indices.push(a);
  34741. indices.push(d);
  34742. indices.push(c);
  34743. indices.push(b);
  34744. }
  34745. }
  34746. // Normals
  34747. VertexData.ComputeNormals(positions, indices, normals);
  34748. // Sides
  34749. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34750. // Result
  34751. var vertexData = new VertexData();
  34752. vertexData.indices = indices;
  34753. vertexData.positions = positions;
  34754. vertexData.normals = normals;
  34755. vertexData.uvs = uvs;
  34756. return vertexData;
  34757. };
  34758. // Tools
  34759. /**
  34760. * @param {any} - positions (number[] or Float32Array)
  34761. * @param {any} - indices (number[] or Uint16Array)
  34762. * @param {any} - normals (number[] or Float32Array)
  34763. * options (optional) :
  34764. * facetPositions : optional array of facet positions (vector3)
  34765. * facetNormals : optional array of facet normals (vector3)
  34766. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34767. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34768. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34769. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34770. * bInfo : optional bounding info, required for facetPartitioning computation
  34771. * useRightHandedSystem: optional boolean to for right handed system computation
  34772. * depthSort : optional boolean to enable the facet depth sort computation
  34773. * distanceTo : optional Vector3 to compute the facet depth from this location
  34774. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34775. */
  34776. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34777. // temporary scalar variables
  34778. var index = 0; // facet index
  34779. var p1p2x = 0.0; // p1p2 vector x coordinate
  34780. var p1p2y = 0.0; // p1p2 vector y coordinate
  34781. var p1p2z = 0.0; // p1p2 vector z coordinate
  34782. var p3p2x = 0.0; // p3p2 vector x coordinate
  34783. var p3p2y = 0.0; // p3p2 vector y coordinate
  34784. var p3p2z = 0.0; // p3p2 vector z coordinate
  34785. var faceNormalx = 0.0; // facet normal x coordinate
  34786. var faceNormaly = 0.0; // facet normal y coordinate
  34787. var faceNormalz = 0.0; // facet normal z coordinate
  34788. var length = 0.0; // facet normal length before normalization
  34789. var v1x = 0; // vector1 x index in the positions array
  34790. var v1y = 0; // vector1 y index in the positions array
  34791. var v1z = 0; // vector1 z index in the positions array
  34792. var v2x = 0; // vector2 x index in the positions array
  34793. var v2y = 0; // vector2 y index in the positions array
  34794. var v2z = 0; // vector2 z index in the positions array
  34795. var v3x = 0; // vector3 x index in the positions array
  34796. var v3y = 0; // vector3 y index in the positions array
  34797. var v3z = 0; // vector3 z index in the positions array
  34798. var computeFacetNormals = false;
  34799. var computeFacetPositions = false;
  34800. var computeFacetPartitioning = false;
  34801. var computeDepthSort = false;
  34802. var faceNormalSign = 1;
  34803. var ratio = 0;
  34804. var distanceTo = null;
  34805. if (options) {
  34806. computeFacetNormals = (options.facetNormals) ? true : false;
  34807. computeFacetPositions = (options.facetPositions) ? true : false;
  34808. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34809. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34810. ratio = options.ratio || 0;
  34811. computeDepthSort = (options.depthSort) ? true : false;
  34812. distanceTo = (options.distanceTo);
  34813. if (computeDepthSort) {
  34814. if (distanceTo === undefined) {
  34815. distanceTo = BABYLON.Vector3.Zero();
  34816. }
  34817. var depthSortedFacets = options.depthSortedFacets;
  34818. }
  34819. }
  34820. // facetPartitioning reinit if needed
  34821. var xSubRatio = 0;
  34822. var ySubRatio = 0;
  34823. var zSubRatio = 0;
  34824. var subSq = 0;
  34825. if (computeFacetPartitioning && options && options.bbSize) {
  34826. var ox = 0; // X partitioning index for facet position
  34827. var oy = 0; // Y partinioning index for facet position
  34828. var oz = 0; // Z partinioning index for facet position
  34829. var b1x = 0; // X partitioning index for facet v1 vertex
  34830. var b1y = 0; // Y partitioning index for facet v1 vertex
  34831. var b1z = 0; // z partitioning index for facet v1 vertex
  34832. var b2x = 0; // X partitioning index for facet v2 vertex
  34833. var b2y = 0; // Y partitioning index for facet v2 vertex
  34834. var b2z = 0; // Z partitioning index for facet v2 vertex
  34835. var b3x = 0; // X partitioning index for facet v3 vertex
  34836. var b3y = 0; // Y partitioning index for facet v3 vertex
  34837. var b3z = 0; // Z partitioning index for facet v3 vertex
  34838. var block_idx_o = 0; // facet barycenter block index
  34839. var block_idx_v1 = 0; // v1 vertex block index
  34840. var block_idx_v2 = 0; // v2 vertex block index
  34841. var block_idx_v3 = 0; // v3 vertex block index
  34842. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34843. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34844. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34845. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34846. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34847. subSq = options.subDiv.max * options.subDiv.max;
  34848. options.facetPartitioning.length = 0;
  34849. }
  34850. // reset the normals
  34851. for (index = 0; index < positions.length; index++) {
  34852. normals[index] = 0.0;
  34853. }
  34854. // Loop : 1 indice triplet = 1 facet
  34855. var nbFaces = (indices.length / 3) | 0;
  34856. for (index = 0; index < nbFaces; index++) {
  34857. // get the indexes of the coordinates of each vertex of the facet
  34858. v1x = indices[index * 3] * 3;
  34859. v1y = v1x + 1;
  34860. v1z = v1x + 2;
  34861. v2x = indices[index * 3 + 1] * 3;
  34862. v2y = v2x + 1;
  34863. v2z = v2x + 2;
  34864. v3x = indices[index * 3 + 2] * 3;
  34865. v3y = v3x + 1;
  34866. v3z = v3x + 2;
  34867. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34868. p1p2y = positions[v1y] - positions[v2y];
  34869. p1p2z = positions[v1z] - positions[v2z];
  34870. p3p2x = positions[v3x] - positions[v2x];
  34871. p3p2y = positions[v3y] - positions[v2y];
  34872. p3p2z = positions[v3z] - positions[v2z];
  34873. // compute the face normal with the cross product
  34874. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34875. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34876. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34877. // normalize this normal and store it in the array facetData
  34878. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34879. length = (length === 0) ? 1.0 : length;
  34880. faceNormalx /= length;
  34881. faceNormaly /= length;
  34882. faceNormalz /= length;
  34883. if (computeFacetNormals && options) {
  34884. options.facetNormals[index].x = faceNormalx;
  34885. options.facetNormals[index].y = faceNormaly;
  34886. options.facetNormals[index].z = faceNormalz;
  34887. }
  34888. if (computeFacetPositions && options) {
  34889. // compute and the facet barycenter coordinates in the array facetPositions
  34890. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34891. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34892. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34893. }
  34894. if (computeFacetPartitioning && options) {
  34895. // store the facet indexes in arrays in the main facetPartitioning array :
  34896. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34897. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34898. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34899. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34900. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34901. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34902. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34903. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34904. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34905. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34906. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34907. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34908. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34909. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34910. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34911. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34912. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34913. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34914. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34915. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34916. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34917. // push each facet index in each block containing the vertex
  34918. options.facetPartitioning[block_idx_v1].push(index);
  34919. if (block_idx_v2 != block_idx_v1) {
  34920. options.facetPartitioning[block_idx_v2].push(index);
  34921. }
  34922. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34923. options.facetPartitioning[block_idx_v3].push(index);
  34924. }
  34925. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34926. options.facetPartitioning[block_idx_o].push(index);
  34927. }
  34928. }
  34929. if (computeDepthSort && options && options.facetPositions) {
  34930. var dsf = depthSortedFacets[index];
  34931. dsf.ind = index * 3;
  34932. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34933. }
  34934. // compute the normals anyway
  34935. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34936. normals[v1y] += faceNormaly;
  34937. normals[v1z] += faceNormalz;
  34938. normals[v2x] += faceNormalx;
  34939. normals[v2y] += faceNormaly;
  34940. normals[v2z] += faceNormalz;
  34941. normals[v3x] += faceNormalx;
  34942. normals[v3y] += faceNormaly;
  34943. normals[v3z] += faceNormalz;
  34944. }
  34945. // last normalization of each normal
  34946. for (index = 0; index < normals.length / 3; index++) {
  34947. faceNormalx = normals[index * 3];
  34948. faceNormaly = normals[index * 3 + 1];
  34949. faceNormalz = normals[index * 3 + 2];
  34950. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34951. length = (length === 0) ? 1.0 : length;
  34952. faceNormalx /= length;
  34953. faceNormaly /= length;
  34954. faceNormalz /= length;
  34955. normals[index * 3] = faceNormalx;
  34956. normals[index * 3 + 1] = faceNormaly;
  34957. normals[index * 3 + 2] = faceNormalz;
  34958. }
  34959. };
  34960. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34961. var li = indices.length;
  34962. var ln = normals.length;
  34963. var i;
  34964. var n;
  34965. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34966. switch (sideOrientation) {
  34967. case BABYLON.Mesh.FRONTSIDE:
  34968. // nothing changed
  34969. break;
  34970. case BABYLON.Mesh.BACKSIDE:
  34971. var tmp;
  34972. // indices
  34973. for (i = 0; i < li; i += 3) {
  34974. tmp = indices[i];
  34975. indices[i] = indices[i + 2];
  34976. indices[i + 2] = tmp;
  34977. }
  34978. // normals
  34979. for (n = 0; n < ln; n++) {
  34980. normals[n] = -normals[n];
  34981. }
  34982. break;
  34983. case BABYLON.Mesh.DOUBLESIDE:
  34984. // positions
  34985. var lp = positions.length;
  34986. var l = lp / 3;
  34987. for (var p = 0; p < lp; p++) {
  34988. positions[lp + p] = positions[p];
  34989. }
  34990. // indices
  34991. for (i = 0; i < li; i += 3) {
  34992. indices[i + li] = indices[i + 2] + l;
  34993. indices[i + 1 + li] = indices[i + 1] + l;
  34994. indices[i + 2 + li] = indices[i] + l;
  34995. }
  34996. // normals
  34997. for (n = 0; n < ln; n++) {
  34998. normals[ln + n] = -normals[n];
  34999. }
  35000. // uvs
  35001. var lu = uvs.length;
  35002. var u = 0;
  35003. for (u = 0; u < lu; u++) {
  35004. uvs[u + lu] = uvs[u];
  35005. }
  35006. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  35007. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  35008. u = 0;
  35009. for (i = 0; i < lu / 2; i++) {
  35010. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  35011. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  35012. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  35013. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  35014. u += 2;
  35015. }
  35016. break;
  35017. }
  35018. };
  35019. /**
  35020. * Creates a new VertexData from the imported parameters.
  35021. */
  35022. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  35023. var vertexData = new VertexData();
  35024. // positions
  35025. var positions = parsedVertexData.positions;
  35026. if (positions) {
  35027. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  35028. }
  35029. // normals
  35030. var normals = parsedVertexData.normals;
  35031. if (normals) {
  35032. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  35033. }
  35034. // tangents
  35035. var tangents = parsedVertexData.tangents;
  35036. if (tangents) {
  35037. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  35038. }
  35039. // uvs
  35040. var uvs = parsedVertexData.uvs;
  35041. if (uvs) {
  35042. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  35043. }
  35044. // uv2s
  35045. var uv2s = parsedVertexData.uv2s;
  35046. if (uv2s) {
  35047. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  35048. }
  35049. // uv3s
  35050. var uv3s = parsedVertexData.uv3s;
  35051. if (uv3s) {
  35052. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  35053. }
  35054. // uv4s
  35055. var uv4s = parsedVertexData.uv4s;
  35056. if (uv4s) {
  35057. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  35058. }
  35059. // uv5s
  35060. var uv5s = parsedVertexData.uv5s;
  35061. if (uv5s) {
  35062. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  35063. }
  35064. // uv6s
  35065. var uv6s = parsedVertexData.uv6s;
  35066. if (uv6s) {
  35067. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  35068. }
  35069. // colors
  35070. var colors = parsedVertexData.colors;
  35071. if (colors) {
  35072. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  35073. }
  35074. // matricesIndices
  35075. var matricesIndices = parsedVertexData.matricesIndices;
  35076. if (matricesIndices) {
  35077. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  35078. }
  35079. // matricesWeights
  35080. var matricesWeights = parsedVertexData.matricesWeights;
  35081. if (matricesWeights) {
  35082. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  35083. }
  35084. // indices
  35085. var indices = parsedVertexData.indices;
  35086. if (indices) {
  35087. vertexData.indices = indices;
  35088. }
  35089. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  35090. };
  35091. return VertexData;
  35092. }());
  35093. BABYLON.VertexData = VertexData;
  35094. })(BABYLON || (BABYLON = {}));
  35095. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  35096. "use strict";
  35097. var BABYLON;
  35098. (function (BABYLON) {
  35099. /**
  35100. * Class used to store geometry data (vertex buffers + index buffer)
  35101. */
  35102. var Geometry = /** @class */ (function () {
  35103. /**
  35104. * Creates a new geometry
  35105. * @param id defines the unique ID
  35106. * @param scene defines the hosting scene
  35107. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  35108. * @param updatable defines if geometry must be updatable (false by default)
  35109. * @param mesh defines the mesh that will be associated with the geometry
  35110. */
  35111. function Geometry(id, scene, vertexData, updatable, mesh) {
  35112. if (updatable === void 0) { updatable = false; }
  35113. if (mesh === void 0) { mesh = null; }
  35114. /**
  35115. * Gets the delay loading state of the geometry (none by default which means not delayed)
  35116. */
  35117. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35118. this._totalVertices = 0;
  35119. this._isDisposed = false;
  35120. this._indexBufferIsUpdatable = false;
  35121. this.id = id;
  35122. this._engine = scene.getEngine();
  35123. this._meshes = [];
  35124. this._scene = scene;
  35125. //Init vertex buffer cache
  35126. this._vertexBuffers = {};
  35127. this._indices = [];
  35128. this._updatable = updatable;
  35129. // vertexData
  35130. if (vertexData) {
  35131. this.setAllVerticesData(vertexData, updatable);
  35132. }
  35133. else {
  35134. this._totalVertices = 0;
  35135. this._indices = [];
  35136. }
  35137. if (this._engine.getCaps().vertexArrayObject) {
  35138. this._vertexArrayObjects = {};
  35139. }
  35140. // applyToMesh
  35141. if (mesh) {
  35142. if (mesh.getClassName() === "LinesMesh") {
  35143. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  35144. this.updateExtend();
  35145. }
  35146. this.applyToMesh(mesh);
  35147. mesh.computeWorldMatrix(true);
  35148. }
  35149. }
  35150. Object.defineProperty(Geometry.prototype, "boundingBias", {
  35151. /**
  35152. * 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
  35153. */
  35154. get: function () {
  35155. return this._boundingBias;
  35156. },
  35157. /**
  35158. * 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
  35159. */
  35160. set: function (value) {
  35161. if (this._boundingBias && this._boundingBias.equals(value)) {
  35162. return;
  35163. }
  35164. this._boundingBias = value.clone();
  35165. this.updateBoundingInfo(true, null);
  35166. },
  35167. enumerable: true,
  35168. configurable: true
  35169. });
  35170. /**
  35171. * Static function used to attach a new empty geometry to a mesh
  35172. * @param mesh defines the mesh to attach the geometry to
  35173. * @returns the new {BABYLON.Geometry}
  35174. */
  35175. Geometry.CreateGeometryForMesh = function (mesh) {
  35176. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  35177. geometry.applyToMesh(mesh);
  35178. return geometry;
  35179. };
  35180. Object.defineProperty(Geometry.prototype, "extend", {
  35181. /**
  35182. * Gets the current extend of the geometry
  35183. */
  35184. get: function () {
  35185. return this._extend;
  35186. },
  35187. enumerable: true,
  35188. configurable: true
  35189. });
  35190. /**
  35191. * Gets the hosting scene
  35192. * @returns the hosting {BABYLON.Scene}
  35193. */
  35194. Geometry.prototype.getScene = function () {
  35195. return this._scene;
  35196. };
  35197. /**
  35198. * Gets the hosting engine
  35199. * @returns the hosting {BABYLON.Engine}
  35200. */
  35201. Geometry.prototype.getEngine = function () {
  35202. return this._engine;
  35203. };
  35204. /**
  35205. * Defines if the geometry is ready to use
  35206. * @returns true if the geometry is ready to be used
  35207. */
  35208. Geometry.prototype.isReady = function () {
  35209. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  35210. };
  35211. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  35212. /**
  35213. * Gets a value indicating that the geometry should not be serialized
  35214. */
  35215. get: function () {
  35216. for (var index = 0; index < this._meshes.length; index++) {
  35217. if (!this._meshes[index].doNotSerialize) {
  35218. return false;
  35219. }
  35220. }
  35221. return true;
  35222. },
  35223. enumerable: true,
  35224. configurable: true
  35225. });
  35226. /** @ignore */
  35227. Geometry.prototype._rebuild = function () {
  35228. if (this._vertexArrayObjects) {
  35229. this._vertexArrayObjects = {};
  35230. }
  35231. // Index buffer
  35232. if (this._meshes.length !== 0 && this._indices) {
  35233. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35234. }
  35235. // Vertex buffers
  35236. for (var key in this._vertexBuffers) {
  35237. var vertexBuffer = this._vertexBuffers[key];
  35238. vertexBuffer._rebuild();
  35239. }
  35240. };
  35241. /**
  35242. * Affects all gemetry data in one call
  35243. * @param vertexData defines the geometry data
  35244. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  35245. */
  35246. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35247. vertexData.applyToGeometry(this, updatable);
  35248. this.notifyUpdate();
  35249. };
  35250. /**
  35251. * Set specific vertex data
  35252. * @param kind defines the data kind (Position, normal, etc...)
  35253. * @param data defines the vertex data to use
  35254. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  35255. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  35256. */
  35257. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  35258. if (updatable === void 0) { updatable = false; }
  35259. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  35260. this.setVerticesBuffer(buffer);
  35261. };
  35262. /**
  35263. * Removes a specific vertex data
  35264. * @param kind defines the data kind (Position, normal, etc...)
  35265. */
  35266. Geometry.prototype.removeVerticesData = function (kind) {
  35267. if (this._vertexBuffers[kind]) {
  35268. this._vertexBuffers[kind].dispose();
  35269. delete this._vertexBuffers[kind];
  35270. }
  35271. };
  35272. /**
  35273. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  35274. * @param buffer defines the vertex buffer to use
  35275. */
  35276. Geometry.prototype.setVerticesBuffer = function (buffer) {
  35277. var kind = buffer.getKind();
  35278. if (this._vertexBuffers[kind]) {
  35279. this._vertexBuffers[kind].dispose();
  35280. }
  35281. this._vertexBuffers[kind] = buffer;
  35282. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35283. var data = buffer.getData();
  35284. var stride = buffer.getStrideSize();
  35285. this._totalVertices = data.length / stride;
  35286. this.updateExtend(data, stride);
  35287. this._resetPointsArrayCache();
  35288. var meshes = this._meshes;
  35289. var numOfMeshes = meshes.length;
  35290. for (var index = 0; index < numOfMeshes; index++) {
  35291. var mesh = meshes[index];
  35292. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35293. mesh._createGlobalSubMesh(false);
  35294. mesh.computeWorldMatrix(true);
  35295. }
  35296. }
  35297. this.notifyUpdate(kind);
  35298. if (this._vertexArrayObjects) {
  35299. this._disposeVertexArrayObjects();
  35300. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  35301. }
  35302. };
  35303. /**
  35304. * Update a specific vertex buffer
  35305. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  35306. * It will do nothing if the buffer is not updatable
  35307. * @param kind defines the data kind (Position, normal, etc...)
  35308. * @param data defines the data to use
  35309. * @param offset defines the offset in the target buffer where to store the data
  35310. */
  35311. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  35312. var vertexBuffer = this.getVertexBuffer(kind);
  35313. if (!vertexBuffer) {
  35314. return;
  35315. }
  35316. vertexBuffer.updateDirectly(data, offset);
  35317. this.notifyUpdate(kind);
  35318. };
  35319. /**
  35320. * Update a specific vertex buffer
  35321. * This function will create a new buffer if the current one is not updatable
  35322. * @param kind defines the data kind (Position, normal, etc...)
  35323. * @param data defines the data to use
  35324. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  35325. */
  35326. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  35327. if (updateExtends === void 0) { updateExtends = false; }
  35328. var vertexBuffer = this.getVertexBuffer(kind);
  35329. if (!vertexBuffer) {
  35330. return;
  35331. }
  35332. vertexBuffer.update(data);
  35333. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35334. var stride = vertexBuffer.getStrideSize();
  35335. this._totalVertices = data.length / stride;
  35336. this.updateBoundingInfo(updateExtends, data);
  35337. }
  35338. this.notifyUpdate(kind);
  35339. };
  35340. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  35341. if (updateExtends) {
  35342. this.updateExtend(data);
  35343. }
  35344. var meshes = this._meshes;
  35345. var numOfMeshes = meshes.length;
  35346. this._resetPointsArrayCache();
  35347. for (var index = 0; index < numOfMeshes; index++) {
  35348. var mesh = meshes[index];
  35349. if (updateExtends) {
  35350. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35351. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  35352. var subMesh = mesh.subMeshes[subIndex];
  35353. subMesh.refreshBoundingInfo();
  35354. }
  35355. }
  35356. }
  35357. };
  35358. /** @ignore */
  35359. Geometry.prototype._bind = function (effect, indexToBind) {
  35360. if (!effect) {
  35361. return;
  35362. }
  35363. if (indexToBind === undefined) {
  35364. indexToBind = this._indexBuffer;
  35365. }
  35366. var vbs = this.getVertexBuffers();
  35367. if (!vbs) {
  35368. return;
  35369. }
  35370. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  35371. this._engine.bindBuffers(vbs, indexToBind, effect);
  35372. return;
  35373. }
  35374. // Using VAO
  35375. if (!this._vertexArrayObjects[effect.key]) {
  35376. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  35377. }
  35378. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  35379. };
  35380. /**
  35381. * Gets total number of vertices
  35382. * @returns the total number of vertices
  35383. */
  35384. Geometry.prototype.getTotalVertices = function () {
  35385. if (!this.isReady()) {
  35386. return 0;
  35387. }
  35388. return this._totalVertices;
  35389. };
  35390. /**
  35391. * Gets a specific vertex data attached to this geometry
  35392. * @param kind defines the data kind (Position, normal, etc...)
  35393. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35394. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  35395. * @returns a float array containing vertex data
  35396. */
  35397. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  35398. var vertexBuffer = this.getVertexBuffer(kind);
  35399. if (!vertexBuffer) {
  35400. return null;
  35401. }
  35402. var orig = vertexBuffer.getData();
  35403. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  35404. return orig;
  35405. }
  35406. else {
  35407. var len = orig.length;
  35408. var copy = [];
  35409. for (var i = 0; i < len; i++) {
  35410. copy.push(orig[i]);
  35411. }
  35412. return copy;
  35413. }
  35414. };
  35415. /**
  35416. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  35417. * @param kind defines the data kind (Position, normal, etc...)
  35418. * @returns true if the vertex buffer with the specified kind is updatable
  35419. */
  35420. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  35421. var vb = this._vertexBuffers[kind];
  35422. if (!vb) {
  35423. return false;
  35424. }
  35425. return vb.isUpdatable();
  35426. };
  35427. /**
  35428. * Gets a specific vertex buffer
  35429. * @param kind defines the data kind (Position, normal, etc...)
  35430. * @returns a {BABYLON.VertexBuffer}
  35431. */
  35432. Geometry.prototype.getVertexBuffer = function (kind) {
  35433. if (!this.isReady()) {
  35434. return null;
  35435. }
  35436. return this._vertexBuffers[kind];
  35437. };
  35438. /**
  35439. * Returns all vertex buffers
  35440. * @return an object holding all vertex buffers indexed by kind
  35441. */
  35442. Geometry.prototype.getVertexBuffers = function () {
  35443. if (!this.isReady()) {
  35444. return null;
  35445. }
  35446. return this._vertexBuffers;
  35447. };
  35448. /**
  35449. * Gets a boolean indicating if specific vertex buffer is present
  35450. * @param kind defines the data kind (Position, normal, etc...)
  35451. * @returns true if data is present
  35452. */
  35453. Geometry.prototype.isVerticesDataPresent = function (kind) {
  35454. if (!this._vertexBuffers) {
  35455. if (this._delayInfo) {
  35456. return this._delayInfo.indexOf(kind) !== -1;
  35457. }
  35458. return false;
  35459. }
  35460. return this._vertexBuffers[kind] !== undefined;
  35461. };
  35462. /**
  35463. * Gets a list of all attached data kinds (Position, normal, etc...)
  35464. * @returns a list of string containing all kinds
  35465. */
  35466. Geometry.prototype.getVerticesDataKinds = function () {
  35467. var result = [];
  35468. var kind;
  35469. if (!this._vertexBuffers && this._delayInfo) {
  35470. for (kind in this._delayInfo) {
  35471. result.push(kind);
  35472. }
  35473. }
  35474. else {
  35475. for (kind in this._vertexBuffers) {
  35476. result.push(kind);
  35477. }
  35478. }
  35479. return result;
  35480. };
  35481. /**
  35482. * Update index buffer
  35483. * @param indices defines the indices to store in the index buffer
  35484. * @param offset defines the offset in the target buffer where to store the data
  35485. */
  35486. Geometry.prototype.updateIndices = function (indices, offset) {
  35487. if (!this._indexBuffer) {
  35488. return;
  35489. }
  35490. if (!this._indexBufferIsUpdatable) {
  35491. this.setIndices(indices, null, true);
  35492. }
  35493. else {
  35494. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  35495. }
  35496. };
  35497. /**
  35498. * Creates a new index buffer
  35499. * @param indices defines the indices to store in the index buffer
  35500. * @param totalVertices defines the total number of vertices (could be null)
  35501. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  35502. */
  35503. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  35504. if (totalVertices === void 0) { totalVertices = null; }
  35505. if (updatable === void 0) { updatable = false; }
  35506. if (this._indexBuffer) {
  35507. this._engine._releaseBuffer(this._indexBuffer);
  35508. }
  35509. this._disposeVertexArrayObjects();
  35510. this._indices = indices;
  35511. this._indexBufferIsUpdatable = updatable;
  35512. if (this._meshes.length !== 0 && this._indices) {
  35513. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  35514. }
  35515. if (totalVertices != undefined) {
  35516. this._totalVertices = totalVertices;
  35517. }
  35518. var meshes = this._meshes;
  35519. var numOfMeshes = meshes.length;
  35520. for (var index = 0; index < numOfMeshes; index++) {
  35521. meshes[index]._createGlobalSubMesh(true);
  35522. }
  35523. this.notifyUpdate();
  35524. };
  35525. /**
  35526. * Return the total number of indices
  35527. * @returns the total number of indices
  35528. */
  35529. Geometry.prototype.getTotalIndices = function () {
  35530. if (!this.isReady()) {
  35531. return 0;
  35532. }
  35533. return this._indices.length;
  35534. };
  35535. /**
  35536. * Gets the index buffer array
  35537. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35538. * @returns the index buffer array
  35539. */
  35540. Geometry.prototype.getIndices = function (copyWhenShared) {
  35541. if (!this.isReady()) {
  35542. return null;
  35543. }
  35544. var orig = this._indices;
  35545. if (!copyWhenShared || this._meshes.length === 1) {
  35546. return orig;
  35547. }
  35548. else {
  35549. var len = orig.length;
  35550. var copy = [];
  35551. for (var i = 0; i < len; i++) {
  35552. copy.push(orig[i]);
  35553. }
  35554. return copy;
  35555. }
  35556. };
  35557. /**
  35558. * Gets the index buffer
  35559. * @return the index buffer
  35560. */
  35561. Geometry.prototype.getIndexBuffer = function () {
  35562. if (!this.isReady()) {
  35563. return null;
  35564. }
  35565. return this._indexBuffer;
  35566. };
  35567. /** @ignore */
  35568. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  35569. if (effect === void 0) { effect = null; }
  35570. if (!effect || !this._vertexArrayObjects) {
  35571. return;
  35572. }
  35573. if (this._vertexArrayObjects[effect.key]) {
  35574. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35575. delete this._vertexArrayObjects[effect.key];
  35576. }
  35577. };
  35578. /**
  35579. * Release the associated resources for a specific mesh
  35580. * @param mesh defines the source mesh
  35581. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35582. */
  35583. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35584. var meshes = this._meshes;
  35585. var index = meshes.indexOf(mesh);
  35586. if (index === -1) {
  35587. return;
  35588. }
  35589. meshes.splice(index, 1);
  35590. mesh._geometry = null;
  35591. if (meshes.length === 0 && shouldDispose) {
  35592. this.dispose();
  35593. }
  35594. };
  35595. /**
  35596. * Apply current geometry to a given mesh
  35597. * @param mesh defines the mesh to apply geometry to
  35598. */
  35599. Geometry.prototype.applyToMesh = function (mesh) {
  35600. if (mesh._geometry === this) {
  35601. return;
  35602. }
  35603. var previousGeometry = mesh._geometry;
  35604. if (previousGeometry) {
  35605. previousGeometry.releaseForMesh(mesh);
  35606. }
  35607. var meshes = this._meshes;
  35608. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35609. mesh._geometry = this;
  35610. this._scene.pushGeometry(this);
  35611. meshes.push(mesh);
  35612. if (this.isReady()) {
  35613. this._applyToMesh(mesh);
  35614. }
  35615. else {
  35616. mesh._boundingInfo = this._boundingInfo;
  35617. }
  35618. };
  35619. Geometry.prototype.updateExtend = function (data, stride) {
  35620. if (data === void 0) { data = null; }
  35621. if (!data) {
  35622. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35623. }
  35624. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35625. };
  35626. Geometry.prototype._applyToMesh = function (mesh) {
  35627. var numOfMeshes = this._meshes.length;
  35628. // vertexBuffers
  35629. for (var kind in this._vertexBuffers) {
  35630. if (numOfMeshes === 1) {
  35631. this._vertexBuffers[kind].create();
  35632. }
  35633. var buffer = this._vertexBuffers[kind].getBuffer();
  35634. if (buffer)
  35635. buffer.references = numOfMeshes;
  35636. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35637. if (!this._extend) {
  35638. this.updateExtend(this._vertexBuffers[kind].getData());
  35639. }
  35640. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35641. mesh._createGlobalSubMesh(false);
  35642. //bounding info was just created again, world matrix should be applied again.
  35643. mesh._updateBoundingInfo();
  35644. }
  35645. }
  35646. // indexBuffer
  35647. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35648. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35649. }
  35650. if (this._indexBuffer) {
  35651. this._indexBuffer.references = numOfMeshes;
  35652. }
  35653. };
  35654. Geometry.prototype.notifyUpdate = function (kind) {
  35655. if (this.onGeometryUpdated) {
  35656. this.onGeometryUpdated(this, kind);
  35657. }
  35658. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35659. var mesh = _a[_i];
  35660. mesh._markSubMeshesAsAttributesDirty();
  35661. }
  35662. };
  35663. /**
  35664. * Load the geometry if it was flagged as delay loaded
  35665. * @param scene defines the hosting scene
  35666. * @param onLoaded defines a callback called when the geometry is loaded
  35667. */
  35668. Geometry.prototype.load = function (scene, onLoaded) {
  35669. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35670. return;
  35671. }
  35672. if (this.isReady()) {
  35673. if (onLoaded) {
  35674. onLoaded();
  35675. }
  35676. return;
  35677. }
  35678. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35679. this._queueLoad(scene, onLoaded);
  35680. };
  35681. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35682. var _this = this;
  35683. if (!this.delayLoadingFile) {
  35684. return;
  35685. }
  35686. scene._addPendingData(this);
  35687. scene._loadFile(this.delayLoadingFile, function (data) {
  35688. if (!_this._delayLoadingFunction) {
  35689. return;
  35690. }
  35691. _this._delayLoadingFunction(JSON.parse(data), _this);
  35692. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35693. _this._delayInfo = [];
  35694. scene._removePendingData(_this);
  35695. var meshes = _this._meshes;
  35696. var numOfMeshes = meshes.length;
  35697. for (var index = 0; index < numOfMeshes; index++) {
  35698. _this._applyToMesh(meshes[index]);
  35699. }
  35700. if (onLoaded) {
  35701. onLoaded();
  35702. }
  35703. }, undefined, true);
  35704. };
  35705. /**
  35706. * Invert the geometry to move from a right handed system to a left handed one.
  35707. */
  35708. Geometry.prototype.toLeftHanded = function () {
  35709. // Flip faces
  35710. var tIndices = this.getIndices(false);
  35711. if (tIndices != null && tIndices.length > 0) {
  35712. for (var i = 0; i < tIndices.length; i += 3) {
  35713. var tTemp = tIndices[i + 0];
  35714. tIndices[i + 0] = tIndices[i + 2];
  35715. tIndices[i + 2] = tTemp;
  35716. }
  35717. this.setIndices(tIndices);
  35718. }
  35719. // Negate position.z
  35720. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35721. if (tPositions != null && tPositions.length > 0) {
  35722. for (var i = 0; i < tPositions.length; i += 3) {
  35723. tPositions[i + 2] = -tPositions[i + 2];
  35724. }
  35725. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35726. }
  35727. // Negate normal.z
  35728. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35729. if (tNormals != null && tNormals.length > 0) {
  35730. for (var i = 0; i < tNormals.length; i += 3) {
  35731. tNormals[i + 2] = -tNormals[i + 2];
  35732. }
  35733. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35734. }
  35735. };
  35736. // Cache
  35737. /** @ignore */
  35738. Geometry.prototype._resetPointsArrayCache = function () {
  35739. this._positions = null;
  35740. };
  35741. /** @ignore */
  35742. Geometry.prototype._generatePointsArray = function () {
  35743. if (this._positions)
  35744. return true;
  35745. this._positions = [];
  35746. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35747. if (!data) {
  35748. return false;
  35749. }
  35750. for (var index = 0; index < data.length; index += 3) {
  35751. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35752. }
  35753. return true;
  35754. };
  35755. /**
  35756. * Gets a value indicating if the geometry is disposed
  35757. * @returns true if the geometry was disposed
  35758. */
  35759. Geometry.prototype.isDisposed = function () {
  35760. return this._isDisposed;
  35761. };
  35762. Geometry.prototype._disposeVertexArrayObjects = function () {
  35763. if (this._vertexArrayObjects) {
  35764. for (var kind in this._vertexArrayObjects) {
  35765. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35766. }
  35767. this._vertexArrayObjects = {};
  35768. }
  35769. };
  35770. /**
  35771. * Free all associated resources
  35772. */
  35773. Geometry.prototype.dispose = function () {
  35774. var meshes = this._meshes;
  35775. var numOfMeshes = meshes.length;
  35776. var index;
  35777. for (index = 0; index < numOfMeshes; index++) {
  35778. this.releaseForMesh(meshes[index]);
  35779. }
  35780. this._meshes = [];
  35781. this._disposeVertexArrayObjects();
  35782. for (var kind in this._vertexBuffers) {
  35783. this._vertexBuffers[kind].dispose();
  35784. }
  35785. this._vertexBuffers = {};
  35786. this._totalVertices = 0;
  35787. if (this._indexBuffer) {
  35788. this._engine._releaseBuffer(this._indexBuffer);
  35789. }
  35790. this._indexBuffer = null;
  35791. this._indices = [];
  35792. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35793. this.delayLoadingFile = null;
  35794. this._delayLoadingFunction = null;
  35795. this._delayInfo = [];
  35796. this._boundingInfo = null;
  35797. this._scene.removeGeometry(this);
  35798. this._isDisposed = true;
  35799. };
  35800. /**
  35801. * Clone the current geometry into a new geometry
  35802. * @param id defines the unique ID of the new geometry
  35803. * @returns a new geometry object
  35804. */
  35805. Geometry.prototype.copy = function (id) {
  35806. var vertexData = new BABYLON.VertexData();
  35807. vertexData.indices = [];
  35808. var indices = this.getIndices();
  35809. if (indices) {
  35810. for (var index = 0; index < indices.length; index++) {
  35811. vertexData.indices.push(indices[index]);
  35812. }
  35813. }
  35814. var updatable = false;
  35815. var stopChecking = false;
  35816. var kind;
  35817. for (kind in this._vertexBuffers) {
  35818. // using slice() to make a copy of the array and not just reference it
  35819. var data = this.getVerticesData(kind);
  35820. if (data instanceof Float32Array) {
  35821. vertexData.set(new Float32Array(data), kind);
  35822. }
  35823. else {
  35824. vertexData.set(data.slice(0), kind);
  35825. }
  35826. if (!stopChecking) {
  35827. var vb = this.getVertexBuffer(kind);
  35828. if (vb) {
  35829. updatable = vb.isUpdatable();
  35830. stopChecking = !updatable;
  35831. }
  35832. }
  35833. }
  35834. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35835. geometry.delayLoadState = this.delayLoadState;
  35836. geometry.delayLoadingFile = this.delayLoadingFile;
  35837. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35838. for (kind in this._delayInfo) {
  35839. geometry._delayInfo = geometry._delayInfo || [];
  35840. geometry._delayInfo.push(kind);
  35841. }
  35842. // Bounding info
  35843. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35844. return geometry;
  35845. };
  35846. /**
  35847. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35848. * @return a JSON representation of the current geometry data (without the vertices data)
  35849. */
  35850. Geometry.prototype.serialize = function () {
  35851. var serializationObject = {};
  35852. serializationObject.id = this.id;
  35853. serializationObject.updatable = this._updatable;
  35854. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35855. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35856. }
  35857. return serializationObject;
  35858. };
  35859. Geometry.prototype.toNumberArray = function (origin) {
  35860. if (Array.isArray(origin)) {
  35861. return origin;
  35862. }
  35863. else {
  35864. return Array.prototype.slice.call(origin);
  35865. }
  35866. };
  35867. /**
  35868. * Serialize all vertices data into a JSON oject
  35869. * @returns a JSON representation of the current geometry data
  35870. */
  35871. Geometry.prototype.serializeVerticeData = function () {
  35872. var serializationObject = this.serialize();
  35873. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35874. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35875. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35876. serializationObject.positions._updatable = true;
  35877. }
  35878. }
  35879. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35880. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35881. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35882. serializationObject.normals._updatable = true;
  35883. }
  35884. }
  35885. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35886. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35887. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35888. serializationObject.tangets._updatable = true;
  35889. }
  35890. }
  35891. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35892. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35893. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35894. serializationObject.uvs._updatable = true;
  35895. }
  35896. }
  35897. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35898. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35899. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35900. serializationObject.uv2s._updatable = true;
  35901. }
  35902. }
  35903. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35904. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35905. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35906. serializationObject.uv3s._updatable = true;
  35907. }
  35908. }
  35909. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35910. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35911. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35912. serializationObject.uv4s._updatable = true;
  35913. }
  35914. }
  35915. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35916. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35917. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35918. serializationObject.uv5s._updatable = true;
  35919. }
  35920. }
  35921. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35922. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35923. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35924. serializationObject.uv6s._updatable = true;
  35925. }
  35926. }
  35927. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35928. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35929. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35930. serializationObject.colors._updatable = true;
  35931. }
  35932. }
  35933. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35934. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35935. serializationObject.matricesIndices._isExpanded = true;
  35936. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35937. serializationObject.matricesIndices._updatable = true;
  35938. }
  35939. }
  35940. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35941. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35942. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35943. serializationObject.matricesWeights._updatable = true;
  35944. }
  35945. }
  35946. serializationObject.indices = this.toNumberArray(this.getIndices());
  35947. return serializationObject;
  35948. };
  35949. // Statics
  35950. /**
  35951. * Extracts a clone of a mesh geometry
  35952. * @param mesh defines the source mesh
  35953. * @param id defines the unique ID of the new geometry object
  35954. * @returns the new geometry object
  35955. */
  35956. Geometry.ExtractFromMesh = function (mesh, id) {
  35957. var geometry = mesh._geometry;
  35958. if (!geometry) {
  35959. return null;
  35960. }
  35961. return geometry.copy(id);
  35962. };
  35963. /**
  35964. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35965. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35966. * Be aware Math.random() could cause collisions, but:
  35967. * "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"
  35968. * @returns a string containing a new GUID
  35969. */
  35970. Geometry.RandomId = function () {
  35971. return BABYLON.Tools.RandomId();
  35972. };
  35973. /** @ignore */
  35974. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  35975. var scene = mesh.getScene();
  35976. // Geometry
  35977. var geometryId = parsedGeometry.geometryId;
  35978. if (geometryId) {
  35979. var geometry = scene.getGeometryByID(geometryId);
  35980. if (geometry) {
  35981. geometry.applyToMesh(mesh);
  35982. }
  35983. }
  35984. else if (parsedGeometry instanceof ArrayBuffer) {
  35985. var binaryInfo = mesh._binaryInfo;
  35986. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35987. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35988. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35989. }
  35990. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35991. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35992. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35993. }
  35994. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  35995. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  35996. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  35997. }
  35998. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35999. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  36000. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  36001. }
  36002. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  36003. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  36004. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  36005. }
  36006. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  36007. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  36008. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  36009. }
  36010. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  36011. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  36012. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  36013. }
  36014. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  36015. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  36016. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  36017. }
  36018. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  36019. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  36020. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  36021. }
  36022. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  36023. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  36024. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  36025. }
  36026. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  36027. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  36028. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  36029. }
  36030. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  36031. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  36032. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  36033. }
  36034. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  36035. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  36036. mesh.setIndices(indicesData, null);
  36037. }
  36038. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  36039. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  36040. mesh.subMeshes = [];
  36041. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  36042. var materialIndex = subMeshesData[(i * 5) + 0];
  36043. var verticesStart = subMeshesData[(i * 5) + 1];
  36044. var verticesCount = subMeshesData[(i * 5) + 2];
  36045. var indexStart = subMeshesData[(i * 5) + 3];
  36046. var indexCount = subMeshesData[(i * 5) + 4];
  36047. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  36048. }
  36049. }
  36050. }
  36051. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  36052. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  36053. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  36054. if (parsedGeometry.tangents) {
  36055. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  36056. }
  36057. if (parsedGeometry.uvs) {
  36058. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  36059. }
  36060. if (parsedGeometry.uvs2) {
  36061. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  36062. }
  36063. if (parsedGeometry.uvs3) {
  36064. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  36065. }
  36066. if (parsedGeometry.uvs4) {
  36067. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  36068. }
  36069. if (parsedGeometry.uvs5) {
  36070. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  36071. }
  36072. if (parsedGeometry.uvs6) {
  36073. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  36074. }
  36075. if (parsedGeometry.colors) {
  36076. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  36077. }
  36078. if (parsedGeometry.matricesIndices) {
  36079. if (!parsedGeometry.matricesIndices._isExpanded) {
  36080. var floatIndices = [];
  36081. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  36082. var matricesIndex = parsedGeometry.matricesIndices[i];
  36083. floatIndices.push(matricesIndex & 0x000000FF);
  36084. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36085. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36086. floatIndices.push(matricesIndex >> 24);
  36087. }
  36088. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  36089. }
  36090. else {
  36091. delete parsedGeometry.matricesIndices._isExpanded;
  36092. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  36093. }
  36094. }
  36095. if (parsedGeometry.matricesIndicesExtra) {
  36096. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  36097. var floatIndices = [];
  36098. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  36099. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  36100. floatIndices.push(matricesIndex & 0x000000FF);
  36101. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36102. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36103. floatIndices.push(matricesIndex >> 24);
  36104. }
  36105. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  36106. }
  36107. else {
  36108. delete parsedGeometry.matricesIndices._isExpanded;
  36109. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  36110. }
  36111. }
  36112. if (parsedGeometry.matricesWeights) {
  36113. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  36114. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  36115. }
  36116. if (parsedGeometry.matricesWeightsExtra) {
  36117. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  36118. }
  36119. mesh.setIndices(parsedGeometry.indices, null);
  36120. }
  36121. // SubMeshes
  36122. if (parsedGeometry.subMeshes) {
  36123. mesh.subMeshes = [];
  36124. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  36125. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  36126. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  36127. }
  36128. }
  36129. // Flat shading
  36130. if (mesh._shouldGenerateFlatShading) {
  36131. mesh.convertToFlatShadedMesh();
  36132. delete mesh._shouldGenerateFlatShading;
  36133. }
  36134. // Update
  36135. mesh.computeWorldMatrix(true);
  36136. // Octree
  36137. var sceneOctree = scene.selectionOctree;
  36138. if (sceneOctree !== undefined && sceneOctree !== null) {
  36139. sceneOctree.addMesh(mesh);
  36140. }
  36141. };
  36142. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  36143. var epsilon = 1e-3;
  36144. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  36145. return;
  36146. }
  36147. var noInfluenceBoneIndex = 0.0;
  36148. if (parsedGeometry.skeletonId > -1) {
  36149. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  36150. if (!skeleton) {
  36151. return;
  36152. }
  36153. noInfluenceBoneIndex = skeleton.bones.length;
  36154. }
  36155. else {
  36156. return;
  36157. }
  36158. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  36159. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36160. var matricesWeights = parsedGeometry.matricesWeights;
  36161. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  36162. var influencers = parsedGeometry.numBoneInfluencer;
  36163. var size = matricesWeights.length;
  36164. for (var i = 0; i < size; i += 4) {
  36165. var weight = 0.0;
  36166. var firstZeroWeight = -1;
  36167. for (var j = 0; j < 4; j++) {
  36168. var w = matricesWeights[i + j];
  36169. weight += w;
  36170. if (w < epsilon && firstZeroWeight < 0) {
  36171. firstZeroWeight = j;
  36172. }
  36173. }
  36174. if (matricesWeightsExtra) {
  36175. for (var j = 0; j < 4; j++) {
  36176. var w = matricesWeightsExtra[i + j];
  36177. weight += w;
  36178. if (w < epsilon && firstZeroWeight < 0) {
  36179. firstZeroWeight = j + 4;
  36180. }
  36181. }
  36182. }
  36183. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  36184. firstZeroWeight = influencers - 1;
  36185. }
  36186. if (weight > epsilon) {
  36187. var mweight = 1.0 / weight;
  36188. for (var j = 0; j < 4; j++) {
  36189. matricesWeights[i + j] *= mweight;
  36190. }
  36191. if (matricesWeightsExtra) {
  36192. for (var j = 0; j < 4; j++) {
  36193. matricesWeightsExtra[i + j] *= mweight;
  36194. }
  36195. }
  36196. }
  36197. else {
  36198. if (firstZeroWeight >= 4) {
  36199. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  36200. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  36201. }
  36202. else {
  36203. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  36204. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  36205. }
  36206. }
  36207. }
  36208. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  36209. if (parsedGeometry.matricesWeightsExtra) {
  36210. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  36211. }
  36212. };
  36213. /**
  36214. * Create a new geometry from persisted data (Using .babylon file format)
  36215. * @param parsedVertexData defines the persisted data
  36216. * @param scene defines the hosting scene
  36217. * @param rootUrl defines the root url to use to load assets (like delayed data)
  36218. * @returns the new geometry object
  36219. */
  36220. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  36221. if (scene.getGeometryByID(parsedVertexData.id)) {
  36222. return null; // null since geometry could be something else than a box...
  36223. }
  36224. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  36225. if (BABYLON.Tags) {
  36226. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  36227. }
  36228. if (parsedVertexData.delayLoadingFile) {
  36229. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36230. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  36231. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  36232. geometry._delayInfo = [];
  36233. if (parsedVertexData.hasUVs) {
  36234. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  36235. }
  36236. if (parsedVertexData.hasUVs2) {
  36237. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  36238. }
  36239. if (parsedVertexData.hasUVs3) {
  36240. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  36241. }
  36242. if (parsedVertexData.hasUVs4) {
  36243. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  36244. }
  36245. if (parsedVertexData.hasUVs5) {
  36246. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  36247. }
  36248. if (parsedVertexData.hasUVs6) {
  36249. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  36250. }
  36251. if (parsedVertexData.hasColors) {
  36252. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  36253. }
  36254. if (parsedVertexData.hasMatricesIndices) {
  36255. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36256. }
  36257. if (parsedVertexData.hasMatricesWeights) {
  36258. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36259. }
  36260. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  36261. }
  36262. else {
  36263. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  36264. }
  36265. scene.pushGeometry(geometry, true);
  36266. return geometry;
  36267. };
  36268. return Geometry;
  36269. }());
  36270. BABYLON.Geometry = Geometry;
  36271. // Primitives
  36272. /// Abstract class
  36273. /**
  36274. * Abstract class used to provide common services for all typed geometries
  36275. */
  36276. var _PrimitiveGeometry = /** @class */ (function (_super) {
  36277. __extends(_PrimitiveGeometry, _super);
  36278. /**
  36279. * Creates a new typed geometry
  36280. * @param id defines the unique ID of the geometry
  36281. * @param scene defines the hosting scene
  36282. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36283. * @param mesh defines the hosting mesh (can be null)
  36284. */
  36285. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  36286. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  36287. if (mesh === void 0) { mesh = null; }
  36288. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  36289. _this._canBeRegenerated = _canBeRegenerated;
  36290. _this._beingRegenerated = true;
  36291. _this.regenerate();
  36292. _this._beingRegenerated = false;
  36293. return _this;
  36294. }
  36295. /**
  36296. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  36297. * @returns true if the geometry can be regenerated
  36298. */
  36299. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  36300. return this._canBeRegenerated;
  36301. };
  36302. /**
  36303. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  36304. */
  36305. _PrimitiveGeometry.prototype.regenerate = function () {
  36306. if (!this._canBeRegenerated) {
  36307. return;
  36308. }
  36309. this._beingRegenerated = true;
  36310. this.setAllVerticesData(this._regenerateVertexData(), false);
  36311. this._beingRegenerated = false;
  36312. };
  36313. /**
  36314. * Clone the geometry
  36315. * @param id defines the unique ID of the new geometry
  36316. * @returns the new geometry
  36317. */
  36318. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  36319. return _super.prototype.copy.call(this, id);
  36320. };
  36321. // overrides
  36322. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  36323. if (!this._beingRegenerated) {
  36324. return;
  36325. }
  36326. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  36327. };
  36328. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  36329. if (!this._beingRegenerated) {
  36330. return;
  36331. }
  36332. _super.prototype.setVerticesData.call(this, kind, data, false);
  36333. };
  36334. // to override
  36335. /** @ignore */
  36336. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  36337. throw new Error("Abstract method");
  36338. };
  36339. _PrimitiveGeometry.prototype.copy = function (id) {
  36340. throw new Error("Must be overriden in sub-classes.");
  36341. };
  36342. _PrimitiveGeometry.prototype.serialize = function () {
  36343. var serializationObject = _super.prototype.serialize.call(this);
  36344. serializationObject.canBeRegenerated = this.canBeRegenerated();
  36345. return serializationObject;
  36346. };
  36347. return _PrimitiveGeometry;
  36348. }(Geometry));
  36349. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  36350. /**
  36351. * Creates a ribbon geometry
  36352. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  36353. */
  36354. var RibbonGeometry = /** @class */ (function (_super) {
  36355. __extends(RibbonGeometry, _super);
  36356. /**
  36357. * Creates a ribbon geometry
  36358. * @param id defines the unique ID of the geometry
  36359. * @param scene defines the hosting scene
  36360. * @param pathArray defines the array of paths to use
  36361. * @param closeArray defines if the last path and the first path must be joined
  36362. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  36363. * @param offset defines the offset between points
  36364. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36365. * @param mesh defines the hosting mesh (can be null)
  36366. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36367. */
  36368. function RibbonGeometry(id, scene,
  36369. /**
  36370. * Defines the array of paths to use
  36371. */
  36372. pathArray,
  36373. /**
  36374. * Defines if the last and first points of each path in your pathArray must be joined
  36375. */
  36376. closeArray,
  36377. /**
  36378. * Defines if the last and first points of each path in your pathArray must be joined
  36379. */
  36380. closePath,
  36381. /**
  36382. * Defines the offset between points
  36383. */
  36384. offset, canBeRegenerated, mesh,
  36385. /**
  36386. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36387. */
  36388. side) {
  36389. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36390. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36391. _this.pathArray = pathArray;
  36392. _this.closeArray = closeArray;
  36393. _this.closePath = closePath;
  36394. _this.offset = offset;
  36395. _this.side = side;
  36396. return _this;
  36397. }
  36398. /** @ignore */
  36399. RibbonGeometry.prototype._regenerateVertexData = function () {
  36400. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  36401. };
  36402. RibbonGeometry.prototype.copy = function (id) {
  36403. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  36404. };
  36405. return RibbonGeometry;
  36406. }(_PrimitiveGeometry));
  36407. BABYLON.RibbonGeometry = RibbonGeometry;
  36408. /**
  36409. * Creates a box geometry
  36410. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  36411. */
  36412. var BoxGeometry = /** @class */ (function (_super) {
  36413. __extends(BoxGeometry, _super);
  36414. /**
  36415. * Creates a box geometry
  36416. * @param id defines the unique ID of the geometry
  36417. * @param scene defines the hosting scene
  36418. * @param size defines the zise of the box (width, height and depth are the same)
  36419. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36420. * @param mesh defines the hosting mesh (can be null)
  36421. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36422. */
  36423. function BoxGeometry(id, scene,
  36424. /**
  36425. * Defines the zise of the box (width, height and depth are the same)
  36426. */
  36427. size, canBeRegenerated, mesh,
  36428. /**
  36429. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36430. */
  36431. side) {
  36432. if (mesh === void 0) { mesh = null; }
  36433. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36434. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36435. _this.size = size;
  36436. _this.side = side;
  36437. return _this;
  36438. }
  36439. BoxGeometry.prototype._regenerateVertexData = function () {
  36440. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36441. };
  36442. BoxGeometry.prototype.copy = function (id) {
  36443. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  36444. };
  36445. BoxGeometry.prototype.serialize = function () {
  36446. var serializationObject = _super.prototype.serialize.call(this);
  36447. serializationObject.size = this.size;
  36448. return serializationObject;
  36449. };
  36450. BoxGeometry.Parse = function (parsedBox, scene) {
  36451. if (scene.getGeometryByID(parsedBox.id)) {
  36452. return null; // null since geometry could be something else than a box...
  36453. }
  36454. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36455. if (BABYLON.Tags) {
  36456. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36457. }
  36458. scene.pushGeometry(box, true);
  36459. return box;
  36460. };
  36461. return BoxGeometry;
  36462. }(_PrimitiveGeometry));
  36463. BABYLON.BoxGeometry = BoxGeometry;
  36464. /**
  36465. * Creates a sphere geometry
  36466. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  36467. */
  36468. var SphereGeometry = /** @class */ (function (_super) {
  36469. __extends(SphereGeometry, _super);
  36470. /**
  36471. * Create a new sphere geometry
  36472. * @param id defines the unique ID of the geometry
  36473. * @param scene defines the hosting scene
  36474. * @param segments defines the number of segments to use to create the sphere
  36475. * @param diameter defines the diameter of the sphere
  36476. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36477. * @param mesh defines the hosting mesh (can be null)
  36478. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36479. */
  36480. function SphereGeometry(id, scene,
  36481. /**
  36482. * Defines the number of segments to use to create the sphere
  36483. */
  36484. segments,
  36485. /**
  36486. * Defines the diameter of the sphere
  36487. */
  36488. diameter, canBeRegenerated, mesh,
  36489. /**
  36490. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36491. */
  36492. side) {
  36493. if (mesh === void 0) { mesh = null; }
  36494. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36495. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36496. _this.segments = segments;
  36497. _this.diameter = diameter;
  36498. _this.side = side;
  36499. return _this;
  36500. }
  36501. SphereGeometry.prototype._regenerateVertexData = function () {
  36502. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36503. };
  36504. SphereGeometry.prototype.copy = function (id) {
  36505. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36506. };
  36507. SphereGeometry.prototype.serialize = function () {
  36508. var serializationObject = _super.prototype.serialize.call(this);
  36509. serializationObject.segments = this.segments;
  36510. serializationObject.diameter = this.diameter;
  36511. return serializationObject;
  36512. };
  36513. SphereGeometry.Parse = function (parsedSphere, scene) {
  36514. if (scene.getGeometryByID(parsedSphere.id)) {
  36515. return null; // null since geometry could be something else than a sphere...
  36516. }
  36517. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36518. if (BABYLON.Tags) {
  36519. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36520. }
  36521. scene.pushGeometry(sphere, true);
  36522. return sphere;
  36523. };
  36524. return SphereGeometry;
  36525. }(_PrimitiveGeometry));
  36526. BABYLON.SphereGeometry = SphereGeometry;
  36527. /**
  36528. * Creates a disc geometry
  36529. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  36530. */
  36531. var DiscGeometry = /** @class */ (function (_super) {
  36532. __extends(DiscGeometry, _super);
  36533. /**
  36534. * Creates a new disc geometry
  36535. * @param id defines the unique ID of the geometry
  36536. * @param scene defines the hosting scene
  36537. * @param radius defines the radius of the disc
  36538. * @param tessellation defines the tesselation factor to apply to the disc
  36539. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36540. * @param mesh defines the hosting mesh (can be null)
  36541. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36542. */
  36543. function DiscGeometry(id, scene,
  36544. /**
  36545. * Defines the radius of the disc
  36546. */
  36547. radius,
  36548. /**
  36549. * Defines the tesselation factor to apply to the disc
  36550. */
  36551. tessellation, canBeRegenerated, mesh,
  36552. /**
  36553. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36554. */
  36555. side) {
  36556. if (mesh === void 0) { mesh = null; }
  36557. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36558. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36559. _this.radius = radius;
  36560. _this.tessellation = tessellation;
  36561. _this.side = side;
  36562. return _this;
  36563. }
  36564. DiscGeometry.prototype._regenerateVertexData = function () {
  36565. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36566. };
  36567. DiscGeometry.prototype.copy = function (id) {
  36568. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36569. };
  36570. return DiscGeometry;
  36571. }(_PrimitiveGeometry));
  36572. BABYLON.DiscGeometry = DiscGeometry;
  36573. /**
  36574. * Creates a new cylinder geometry
  36575. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36576. */
  36577. var CylinderGeometry = /** @class */ (function (_super) {
  36578. __extends(CylinderGeometry, _super);
  36579. /**
  36580. * Creates a new cylinder geometry
  36581. * @param id defines the unique ID of the geometry
  36582. * @param scene defines the hosting scene
  36583. * @param height defines the height of the cylinder
  36584. * @param diameterTop defines the diameter of the cylinder's top cap
  36585. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36586. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36587. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36588. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36589. * @param mesh defines the hosting mesh (can be null)
  36590. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36591. */
  36592. function CylinderGeometry(id, scene,
  36593. /**
  36594. * Defines the height of the cylinder
  36595. */
  36596. height,
  36597. /**
  36598. * Defines the diameter of the cylinder's top cap
  36599. */
  36600. diameterTop,
  36601. /**
  36602. * Defines the diameter of the cylinder's bottom cap
  36603. */
  36604. diameterBottom,
  36605. /**
  36606. * Defines the tessellation factor to apply to the cylinder
  36607. */
  36608. tessellation,
  36609. /**
  36610. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36611. */
  36612. subdivisions, canBeRegenerated, mesh,
  36613. /**
  36614. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36615. */
  36616. side) {
  36617. if (subdivisions === void 0) { subdivisions = 1; }
  36618. if (mesh === void 0) { mesh = null; }
  36619. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36620. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36621. _this.height = height;
  36622. _this.diameterTop = diameterTop;
  36623. _this.diameterBottom = diameterBottom;
  36624. _this.tessellation = tessellation;
  36625. _this.subdivisions = subdivisions;
  36626. _this.side = side;
  36627. return _this;
  36628. }
  36629. CylinderGeometry.prototype._regenerateVertexData = function () {
  36630. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36631. };
  36632. CylinderGeometry.prototype.copy = function (id) {
  36633. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36634. };
  36635. CylinderGeometry.prototype.serialize = function () {
  36636. var serializationObject = _super.prototype.serialize.call(this);
  36637. serializationObject.height = this.height;
  36638. serializationObject.diameterTop = this.diameterTop;
  36639. serializationObject.diameterBottom = this.diameterBottom;
  36640. serializationObject.tessellation = this.tessellation;
  36641. return serializationObject;
  36642. };
  36643. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36644. if (scene.getGeometryByID(parsedCylinder.id)) {
  36645. return null; // null since geometry could be something else than a cylinder...
  36646. }
  36647. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36648. if (BABYLON.Tags) {
  36649. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36650. }
  36651. scene.pushGeometry(cylinder, true);
  36652. return cylinder;
  36653. };
  36654. return CylinderGeometry;
  36655. }(_PrimitiveGeometry));
  36656. BABYLON.CylinderGeometry = CylinderGeometry;
  36657. /**
  36658. * Creates a new torus geometry
  36659. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36660. */
  36661. var TorusGeometry = /** @class */ (function (_super) {
  36662. __extends(TorusGeometry, _super);
  36663. /**
  36664. * Creates a new torus geometry
  36665. * @param id defines the unique ID of the geometry
  36666. * @param scene defines the hosting scene
  36667. * @param diameter defines the diameter of the torus
  36668. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36669. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36670. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36671. * @param mesh defines the hosting mesh (can be null)
  36672. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36673. */
  36674. function TorusGeometry(id, scene,
  36675. /**
  36676. * Defines the diameter of the torus
  36677. */
  36678. diameter,
  36679. /**
  36680. * Defines the thickness of the torus (ie. internal diameter)
  36681. */
  36682. thickness,
  36683. /**
  36684. * Defines the tesselation factor to apply to the torus
  36685. */
  36686. tessellation, canBeRegenerated, mesh,
  36687. /**
  36688. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36689. */
  36690. side) {
  36691. if (mesh === void 0) { mesh = null; }
  36692. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36693. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36694. _this.diameter = diameter;
  36695. _this.thickness = thickness;
  36696. _this.tessellation = tessellation;
  36697. _this.side = side;
  36698. return _this;
  36699. }
  36700. TorusGeometry.prototype._regenerateVertexData = function () {
  36701. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36702. };
  36703. TorusGeometry.prototype.copy = function (id) {
  36704. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36705. };
  36706. TorusGeometry.prototype.serialize = function () {
  36707. var serializationObject = _super.prototype.serialize.call(this);
  36708. serializationObject.diameter = this.diameter;
  36709. serializationObject.thickness = this.thickness;
  36710. serializationObject.tessellation = this.tessellation;
  36711. return serializationObject;
  36712. };
  36713. TorusGeometry.Parse = function (parsedTorus, scene) {
  36714. if (scene.getGeometryByID(parsedTorus.id)) {
  36715. return null; // null since geometry could be something else than a torus...
  36716. }
  36717. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36718. if (BABYLON.Tags) {
  36719. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36720. }
  36721. scene.pushGeometry(torus, true);
  36722. return torus;
  36723. };
  36724. return TorusGeometry;
  36725. }(_PrimitiveGeometry));
  36726. BABYLON.TorusGeometry = TorusGeometry;
  36727. /**
  36728. * Creates a new ground geometry
  36729. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36730. */
  36731. var GroundGeometry = /** @class */ (function (_super) {
  36732. __extends(GroundGeometry, _super);
  36733. /**
  36734. * Creates a new ground geometry
  36735. * @param id defines the unique ID of the geometry
  36736. * @param scene defines the hosting scene
  36737. * @param width defines the width of the ground
  36738. * @param height defines the height of the ground
  36739. * @param subdivisions defines the subdivisions to apply to the ground
  36740. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36741. * @param mesh defines the hosting mesh (can be null)
  36742. */
  36743. function GroundGeometry(id, scene,
  36744. /**
  36745. * Defines the width of the ground
  36746. */
  36747. width,
  36748. /**
  36749. * Defines the height of the ground
  36750. */
  36751. height,
  36752. /**
  36753. * Defines the subdivisions to apply to the ground
  36754. */
  36755. subdivisions, canBeRegenerated, mesh) {
  36756. if (mesh === void 0) { mesh = null; }
  36757. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36758. _this.width = width;
  36759. _this.height = height;
  36760. _this.subdivisions = subdivisions;
  36761. return _this;
  36762. }
  36763. GroundGeometry.prototype._regenerateVertexData = function () {
  36764. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36765. };
  36766. GroundGeometry.prototype.copy = function (id) {
  36767. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36768. };
  36769. GroundGeometry.prototype.serialize = function () {
  36770. var serializationObject = _super.prototype.serialize.call(this);
  36771. serializationObject.width = this.width;
  36772. serializationObject.height = this.height;
  36773. serializationObject.subdivisions = this.subdivisions;
  36774. return serializationObject;
  36775. };
  36776. GroundGeometry.Parse = function (parsedGround, scene) {
  36777. if (scene.getGeometryByID(parsedGround.id)) {
  36778. return null; // null since geometry could be something else than a ground...
  36779. }
  36780. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36781. if (BABYLON.Tags) {
  36782. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36783. }
  36784. scene.pushGeometry(ground, true);
  36785. return ground;
  36786. };
  36787. return GroundGeometry;
  36788. }(_PrimitiveGeometry));
  36789. BABYLON.GroundGeometry = GroundGeometry;
  36790. /**
  36791. * Creates a tiled ground geometry
  36792. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36793. */
  36794. var TiledGroundGeometry = /** @class */ (function (_super) {
  36795. __extends(TiledGroundGeometry, _super);
  36796. /**
  36797. * Creates a tiled ground geometry
  36798. * @param id defines the unique ID of the geometry
  36799. * @param scene defines the hosting scene
  36800. * @param xmin defines the minimum value on X axis
  36801. * @param zmin defines the minimum value on Z axis
  36802. * @param xmax defines the maximum value on X axis
  36803. * @param zmax defines the maximum value on Z axis
  36804. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36805. * @param precision defines the precision to use when computing the tiles
  36806. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36807. * @param mesh defines the hosting mesh (can be null)
  36808. */
  36809. function TiledGroundGeometry(id, scene,
  36810. /**
  36811. * Defines the minimum value on X axis
  36812. */
  36813. xmin,
  36814. /**
  36815. * Defines the minimum value on Z axis
  36816. */
  36817. zmin,
  36818. /**
  36819. * Defines the maximum value on X axis
  36820. */
  36821. xmax,
  36822. /**
  36823. * Defines the maximum value on Z axis
  36824. */
  36825. zmax,
  36826. /**
  36827. * Defines the subdivisions to apply to the ground
  36828. */
  36829. subdivisions,
  36830. /**
  36831. * Defines the precision to use when computing the tiles
  36832. */
  36833. precision, canBeRegenerated, mesh) {
  36834. if (mesh === void 0) { mesh = null; }
  36835. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36836. _this.xmin = xmin;
  36837. _this.zmin = zmin;
  36838. _this.xmax = xmax;
  36839. _this.zmax = zmax;
  36840. _this.subdivisions = subdivisions;
  36841. _this.precision = precision;
  36842. return _this;
  36843. }
  36844. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36845. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36846. };
  36847. TiledGroundGeometry.prototype.copy = function (id) {
  36848. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36849. };
  36850. return TiledGroundGeometry;
  36851. }(_PrimitiveGeometry));
  36852. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36853. /**
  36854. * Creates a plane geometry
  36855. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36856. */
  36857. var PlaneGeometry = /** @class */ (function (_super) {
  36858. __extends(PlaneGeometry, _super);
  36859. /**
  36860. * Creates a plane geometry
  36861. * @param id defines the unique ID of the geometry
  36862. * @param scene defines the hosting scene
  36863. * @param size defines the size of the plane (width === height)
  36864. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36865. * @param mesh defines the hosting mesh (can be null)
  36866. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36867. */
  36868. function PlaneGeometry(id, scene,
  36869. /**
  36870. * Defines the size of the plane (width === height)
  36871. */
  36872. size, canBeRegenerated, mesh,
  36873. /**
  36874. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36875. */
  36876. side) {
  36877. if (mesh === void 0) { mesh = null; }
  36878. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36879. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36880. _this.size = size;
  36881. _this.side = side;
  36882. return _this;
  36883. }
  36884. PlaneGeometry.prototype._regenerateVertexData = function () {
  36885. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36886. };
  36887. PlaneGeometry.prototype.copy = function (id) {
  36888. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36889. };
  36890. PlaneGeometry.prototype.serialize = function () {
  36891. var serializationObject = _super.prototype.serialize.call(this);
  36892. serializationObject.size = this.size;
  36893. return serializationObject;
  36894. };
  36895. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36896. if (scene.getGeometryByID(parsedPlane.id)) {
  36897. return null; // null since geometry could be something else than a ground...
  36898. }
  36899. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36900. if (BABYLON.Tags) {
  36901. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36902. }
  36903. scene.pushGeometry(plane, true);
  36904. return plane;
  36905. };
  36906. return PlaneGeometry;
  36907. }(_PrimitiveGeometry));
  36908. BABYLON.PlaneGeometry = PlaneGeometry;
  36909. /**
  36910. * Creates a torus knot geometry
  36911. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36912. */
  36913. var TorusKnotGeometry = /** @class */ (function (_super) {
  36914. __extends(TorusKnotGeometry, _super);
  36915. /**
  36916. * Creates a torus knot geometry
  36917. * @param id defines the unique ID of the geometry
  36918. * @param scene defines the hosting scene
  36919. * @param radius defines the radius of the torus knot
  36920. * @param tube defines the thickness of the torus knot tube
  36921. * @param radialSegments defines the number of radial segments
  36922. * @param tubularSegments defines the number of tubular segments
  36923. * @param p defines the first number of windings
  36924. * @param q defines the second number of windings
  36925. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36926. * @param mesh defines the hosting mesh (can be null)
  36927. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36928. */
  36929. function TorusKnotGeometry(id, scene,
  36930. /**
  36931. * Defines the radius of the torus knot
  36932. */
  36933. radius,
  36934. /**
  36935. * Defines the thickness of the torus knot tube
  36936. */
  36937. tube,
  36938. /**
  36939. * Defines the number of radial segments
  36940. */
  36941. radialSegments,
  36942. /**
  36943. * Defines the number of tubular segments
  36944. */
  36945. tubularSegments,
  36946. /**
  36947. * Defines the first number of windings
  36948. */
  36949. p,
  36950. /**
  36951. * Defines the second number of windings
  36952. */
  36953. q, canBeRegenerated, mesh,
  36954. /**
  36955. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36956. */
  36957. side) {
  36958. if (mesh === void 0) { mesh = null; }
  36959. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36960. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36961. _this.radius = radius;
  36962. _this.tube = tube;
  36963. _this.radialSegments = radialSegments;
  36964. _this.tubularSegments = tubularSegments;
  36965. _this.p = p;
  36966. _this.q = q;
  36967. _this.side = side;
  36968. return _this;
  36969. }
  36970. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36971. 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 });
  36972. };
  36973. TorusKnotGeometry.prototype.copy = function (id) {
  36974. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36975. };
  36976. TorusKnotGeometry.prototype.serialize = function () {
  36977. var serializationObject = _super.prototype.serialize.call(this);
  36978. serializationObject.radius = this.radius;
  36979. serializationObject.tube = this.tube;
  36980. serializationObject.radialSegments = this.radialSegments;
  36981. serializationObject.tubularSegments = this.tubularSegments;
  36982. serializationObject.p = this.p;
  36983. serializationObject.q = this.q;
  36984. return serializationObject;
  36985. };
  36986. ;
  36987. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  36988. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  36989. return null; // null since geometry could be something else than a ground...
  36990. }
  36991. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  36992. if (BABYLON.Tags) {
  36993. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  36994. }
  36995. scene.pushGeometry(torusKnot, true);
  36996. return torusKnot;
  36997. };
  36998. return TorusKnotGeometry;
  36999. }(_PrimitiveGeometry));
  37000. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  37001. //}
  37002. })(BABYLON || (BABYLON = {}));
  37003. //# sourceMappingURL=babylon.geometry.js.map
  37004. "use strict";
  37005. var BABYLON;
  37006. (function (BABYLON) {
  37007. /**
  37008. * PostProcessManager is used to manage one or more post processes or post process pipelines
  37009. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  37010. */
  37011. var PostProcessManager = /** @class */ (function () {
  37012. /**
  37013. * Creates a new instance of @see PostProcess
  37014. * @param scene The scene that the post process is associated with.
  37015. */
  37016. function PostProcessManager(scene) {
  37017. this._vertexBuffers = {};
  37018. this._scene = scene;
  37019. }
  37020. PostProcessManager.prototype._prepareBuffers = function () {
  37021. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  37022. return;
  37023. }
  37024. // VBO
  37025. var vertices = [];
  37026. vertices.push(1, 1);
  37027. vertices.push(-1, 1);
  37028. vertices.push(-1, -1);
  37029. vertices.push(1, -1);
  37030. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  37031. this._buildIndexBuffer();
  37032. };
  37033. PostProcessManager.prototype._buildIndexBuffer = function () {
  37034. // Indices
  37035. var indices = [];
  37036. indices.push(0);
  37037. indices.push(1);
  37038. indices.push(2);
  37039. indices.push(0);
  37040. indices.push(2);
  37041. indices.push(3);
  37042. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  37043. };
  37044. /**
  37045. * Rebuilds the vertex buffers of the manager.
  37046. */
  37047. PostProcessManager.prototype._rebuild = function () {
  37048. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37049. if (!vb) {
  37050. return;
  37051. }
  37052. vb._rebuild();
  37053. this._buildIndexBuffer();
  37054. };
  37055. // Methods
  37056. /**
  37057. * Prepares a frame to be run through a post process.
  37058. * @param sourceTexture The input texture to the post procesess. (default: null)
  37059. * @param postProcesses An array of post processes to be run. (default: null)
  37060. * @returns True if the post processes were able to be run.
  37061. */
  37062. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  37063. if (sourceTexture === void 0) { sourceTexture = null; }
  37064. if (postProcesses === void 0) { postProcesses = null; }
  37065. var camera = this._scene.activeCamera;
  37066. if (!camera) {
  37067. return false;
  37068. }
  37069. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37070. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37071. return false;
  37072. }
  37073. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  37074. return true;
  37075. };
  37076. /**
  37077. * Manually render a set of post processes to a texture.
  37078. * @param postProcesses An array of post processes to be run.
  37079. * @param targetTexture The target texture to render to.
  37080. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  37081. */
  37082. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  37083. if (targetTexture === void 0) { targetTexture = null; }
  37084. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37085. var engine = this._scene.getEngine();
  37086. for (var index = 0; index < postProcesses.length; index++) {
  37087. if (index < postProcesses.length - 1) {
  37088. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  37089. }
  37090. else {
  37091. if (targetTexture) {
  37092. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  37093. }
  37094. else {
  37095. engine.restoreDefaultFramebuffer();
  37096. }
  37097. }
  37098. var pp = postProcesses[index];
  37099. var effect = pp.apply();
  37100. if (effect) {
  37101. pp.onBeforeRenderObservable.notifyObservers(effect);
  37102. // VBOs
  37103. this._prepareBuffers();
  37104. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37105. // Draw order
  37106. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37107. pp.onAfterRenderObservable.notifyObservers(effect);
  37108. }
  37109. }
  37110. // Restore depth buffer
  37111. engine.setDepthBuffer(true);
  37112. engine.setDepthWrite(true);
  37113. };
  37114. /**
  37115. * Finalize the result of the output of the postprocesses.
  37116. * @param doNotPresent If true the result will not be displayed to the screen.
  37117. * @param targetTexture The target texture to render to.
  37118. * @param faceIndex The index of the face to bind the target texture to.
  37119. * @param postProcesses The array of post processes to render.
  37120. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  37121. */
  37122. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  37123. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37124. var camera = this._scene.activeCamera;
  37125. if (!camera) {
  37126. return;
  37127. }
  37128. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37129. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37130. return;
  37131. }
  37132. var engine = this._scene.getEngine();
  37133. for (var index = 0, len = postProcesses.length; index < len; index++) {
  37134. var pp = postProcesses[index];
  37135. if (index < len - 1) {
  37136. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  37137. }
  37138. else {
  37139. if (targetTexture) {
  37140. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  37141. }
  37142. else {
  37143. engine.restoreDefaultFramebuffer();
  37144. }
  37145. }
  37146. if (doNotPresent) {
  37147. break;
  37148. }
  37149. var effect = pp.apply();
  37150. if (effect) {
  37151. pp.onBeforeRenderObservable.notifyObservers(effect);
  37152. // VBOs
  37153. this._prepareBuffers();
  37154. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37155. // Draw order
  37156. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37157. pp.onAfterRenderObservable.notifyObservers(effect);
  37158. }
  37159. }
  37160. // Restore states
  37161. engine.setDepthBuffer(true);
  37162. engine.setDepthWrite(true);
  37163. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  37164. };
  37165. /**
  37166. * Disposes of the post process manager.
  37167. */
  37168. PostProcessManager.prototype.dispose = function () {
  37169. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37170. if (buffer) {
  37171. buffer.dispose();
  37172. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  37173. }
  37174. if (this._indexBuffer) {
  37175. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37176. this._indexBuffer = null;
  37177. }
  37178. };
  37179. return PostProcessManager;
  37180. }());
  37181. BABYLON.PostProcessManager = PostProcessManager;
  37182. })(BABYLON || (BABYLON = {}));
  37183. //# sourceMappingURL=babylon.postProcessManager.js.map
  37184. "use strict";
  37185. var BABYLON;
  37186. (function (BABYLON) {
  37187. /**
  37188. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  37189. */
  37190. var PerformanceMonitor = /** @class */ (function () {
  37191. /**
  37192. * constructor
  37193. * @param frameSampleSize The number of samples required to saturate the sliding window
  37194. */
  37195. function PerformanceMonitor(frameSampleSize) {
  37196. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  37197. this._enabled = true;
  37198. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  37199. }
  37200. /**
  37201. * Samples current frame
  37202. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  37203. */
  37204. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  37205. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  37206. if (!this._enabled)
  37207. return;
  37208. if (this._lastFrameTimeMs != null) {
  37209. var dt = timeMs - this._lastFrameTimeMs;
  37210. this._rollingFrameTime.add(dt);
  37211. }
  37212. this._lastFrameTimeMs = timeMs;
  37213. };
  37214. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  37215. /**
  37216. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37217. * @return Average frame time in milliseconds
  37218. */
  37219. get: function () {
  37220. return this._rollingFrameTime.average;
  37221. },
  37222. enumerable: true,
  37223. configurable: true
  37224. });
  37225. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  37226. /**
  37227. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37228. * @return Frame time variance in milliseconds squared
  37229. */
  37230. get: function () {
  37231. return this._rollingFrameTime.variance;
  37232. },
  37233. enumerable: true,
  37234. configurable: true
  37235. });
  37236. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  37237. /**
  37238. * Returns the frame time of the most recent frame
  37239. * @return Frame time in milliseconds
  37240. */
  37241. get: function () {
  37242. return this._rollingFrameTime.history(0);
  37243. },
  37244. enumerable: true,
  37245. configurable: true
  37246. });
  37247. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  37248. /**
  37249. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  37250. * @return Framerate in frames per second
  37251. */
  37252. get: function () {
  37253. return 1000.0 / this._rollingFrameTime.average;
  37254. },
  37255. enumerable: true,
  37256. configurable: true
  37257. });
  37258. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  37259. /**
  37260. * Returns the average framerate in frames per second using the most recent frame time
  37261. * @return Framerate in frames per second
  37262. */
  37263. get: function () {
  37264. var history = this._rollingFrameTime.history(0);
  37265. if (history === 0) {
  37266. return 0;
  37267. }
  37268. return 1000.0 / history;
  37269. },
  37270. enumerable: true,
  37271. configurable: true
  37272. });
  37273. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  37274. /**
  37275. * Returns true if enough samples have been taken to completely fill the sliding window
  37276. * @return true if saturated
  37277. */
  37278. get: function () {
  37279. return this._rollingFrameTime.isSaturated();
  37280. },
  37281. enumerable: true,
  37282. configurable: true
  37283. });
  37284. /**
  37285. * Enables contributions to the sliding window sample set
  37286. */
  37287. PerformanceMonitor.prototype.enable = function () {
  37288. this._enabled = true;
  37289. };
  37290. /**
  37291. * Disables contributions to the sliding window sample set
  37292. * Samples will not be interpolated over the disabled period
  37293. */
  37294. PerformanceMonitor.prototype.disable = function () {
  37295. this._enabled = false;
  37296. //clear last sample to avoid interpolating over the disabled period when next enabled
  37297. this._lastFrameTimeMs = null;
  37298. };
  37299. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  37300. /**
  37301. * Returns true if sampling is enabled
  37302. * @return true if enabled
  37303. */
  37304. get: function () {
  37305. return this._enabled;
  37306. },
  37307. enumerable: true,
  37308. configurable: true
  37309. });
  37310. /**
  37311. * Resets performance monitor
  37312. */
  37313. PerformanceMonitor.prototype.reset = function () {
  37314. //clear last sample to avoid interpolating over the disabled period when next enabled
  37315. this._lastFrameTimeMs = null;
  37316. //wipe record
  37317. this._rollingFrameTime.reset();
  37318. };
  37319. return PerformanceMonitor;
  37320. }());
  37321. BABYLON.PerformanceMonitor = PerformanceMonitor;
  37322. /**
  37323. * RollingAverage
  37324. *
  37325. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  37326. */
  37327. var RollingAverage = /** @class */ (function () {
  37328. /**
  37329. * constructor
  37330. * @param length The number of samples required to saturate the sliding window
  37331. */
  37332. function RollingAverage(length) {
  37333. this._samples = new Array(length);
  37334. this.reset();
  37335. }
  37336. /**
  37337. * Adds a sample to the sample set
  37338. * @param v The sample value
  37339. */
  37340. RollingAverage.prototype.add = function (v) {
  37341. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  37342. var delta;
  37343. //we need to check if we've already wrapped round
  37344. if (this.isSaturated()) {
  37345. //remove bottom of stack from mean
  37346. var bottomValue = this._samples[this._pos];
  37347. delta = bottomValue - this.average;
  37348. this.average -= delta / (this._sampleCount - 1);
  37349. this._m2 -= delta * (bottomValue - this.average);
  37350. }
  37351. else {
  37352. this._sampleCount++;
  37353. }
  37354. //add new value to mean
  37355. delta = v - this.average;
  37356. this.average += delta / (this._sampleCount);
  37357. this._m2 += delta * (v - this.average);
  37358. //set the new variance
  37359. this.variance = this._m2 / (this._sampleCount - 1);
  37360. this._samples[this._pos] = v;
  37361. this._pos++;
  37362. this._pos %= this._samples.length; //positive wrap around
  37363. };
  37364. /**
  37365. * Returns previously added values or null if outside of history or outside the sliding window domain
  37366. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  37367. * @return Value previously recorded with add() or null if outside of range
  37368. */
  37369. RollingAverage.prototype.history = function (i) {
  37370. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  37371. return 0;
  37372. }
  37373. var i0 = this._wrapPosition(this._pos - 1.0);
  37374. return this._samples[this._wrapPosition(i0 - i)];
  37375. };
  37376. /**
  37377. * Returns true if enough samples have been taken to completely fill the sliding window
  37378. * @return true if sample-set saturated
  37379. */
  37380. RollingAverage.prototype.isSaturated = function () {
  37381. return this._sampleCount >= this._samples.length;
  37382. };
  37383. /**
  37384. * Resets the rolling average (equivalent to 0 samples taken so far)
  37385. */
  37386. RollingAverage.prototype.reset = function () {
  37387. this.average = 0;
  37388. this.variance = 0;
  37389. this._sampleCount = 0;
  37390. this._pos = 0;
  37391. this._m2 = 0;
  37392. };
  37393. /**
  37394. * Wraps a value around the sample range boundaries
  37395. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  37396. * @return Wrapped position in sample range
  37397. */
  37398. RollingAverage.prototype._wrapPosition = function (i) {
  37399. var max = this._samples.length;
  37400. return ((i % max) + max) % max;
  37401. };
  37402. return RollingAverage;
  37403. }());
  37404. BABYLON.RollingAverage = RollingAverage;
  37405. })(BABYLON || (BABYLON = {}));
  37406. //# sourceMappingURL=babylon.performanceMonitor.js.map
  37407. "use strict";
  37408. var BABYLON;
  37409. (function (BABYLON) {
  37410. /**
  37411. * This groups together the common properties used for image processing either in direct forward pass
  37412. * or through post processing effect depending on the use of the image processing pipeline in your scene
  37413. * or not.
  37414. */
  37415. var ImageProcessingConfiguration = /** @class */ (function () {
  37416. function ImageProcessingConfiguration() {
  37417. /**
  37418. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  37419. */
  37420. this.colorCurves = new BABYLON.ColorCurves();
  37421. this._colorCurvesEnabled = false;
  37422. this._colorGradingEnabled = false;
  37423. this._colorGradingWithGreenDepth = true;
  37424. this._colorGradingBGR = true;
  37425. this._exposure = 1.0;
  37426. this._toneMappingEnabled = false;
  37427. this._contrast = 1.0;
  37428. /**
  37429. * Vignette stretch size.
  37430. */
  37431. this.vignetteStretch = 0;
  37432. /**
  37433. * Vignette centre X Offset.
  37434. */
  37435. this.vignetteCentreX = 0;
  37436. /**
  37437. * Vignette centre Y Offset.
  37438. */
  37439. this.vignetteCentreY = 0;
  37440. /**
  37441. * Vignette weight or intensity of the vignette effect.
  37442. */
  37443. this.vignetteWeight = 1.5;
  37444. /**
  37445. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  37446. * if vignetteEnabled is set to true.
  37447. */
  37448. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  37449. /**
  37450. * Camera field of view used by the Vignette effect.
  37451. */
  37452. this.vignetteCameraFov = 0.5;
  37453. this._grainEnabled = false;
  37454. this._grainIntensity = 30;
  37455. this._grainAnimated = false;
  37456. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  37457. this._vignetteEnabled = false;
  37458. this._applyByPostProcess = false;
  37459. this._isEnabled = true;
  37460. /**
  37461. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  37462. * @type {BABYLON.Observable}
  37463. */
  37464. this.onUpdateParameters = new BABYLON.Observable();
  37465. }
  37466. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  37467. /**
  37468. * Gets wether the color curves effect is enabled.
  37469. */
  37470. get: function () {
  37471. return this._colorCurvesEnabled;
  37472. },
  37473. /**
  37474. * Sets wether the color curves effect is enabled.
  37475. */
  37476. set: function (value) {
  37477. if (this._colorCurvesEnabled === value) {
  37478. return;
  37479. }
  37480. this._colorCurvesEnabled = value;
  37481. this._updateParameters();
  37482. },
  37483. enumerable: true,
  37484. configurable: true
  37485. });
  37486. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  37487. /**
  37488. * Gets wether the color grading effect is enabled.
  37489. */
  37490. get: function () {
  37491. return this._colorGradingEnabled;
  37492. },
  37493. /**
  37494. * Sets wether the color grading effect is enabled.
  37495. */
  37496. set: function (value) {
  37497. if (this._colorGradingEnabled === value) {
  37498. return;
  37499. }
  37500. this._colorGradingEnabled = value;
  37501. this._updateParameters();
  37502. },
  37503. enumerable: true,
  37504. configurable: true
  37505. });
  37506. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  37507. /**
  37508. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  37509. */
  37510. get: function () {
  37511. return this._colorGradingWithGreenDepth;
  37512. },
  37513. /**
  37514. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  37515. */
  37516. set: function (value) {
  37517. if (this._colorGradingWithGreenDepth === value) {
  37518. return;
  37519. }
  37520. this._colorGradingWithGreenDepth = value;
  37521. this._updateParameters();
  37522. },
  37523. enumerable: true,
  37524. configurable: true
  37525. });
  37526. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  37527. /**
  37528. * Gets wether the color grading texture contains BGR values.
  37529. */
  37530. get: function () {
  37531. return this._colorGradingBGR;
  37532. },
  37533. /**
  37534. * Sets wether the color grading texture contains BGR values.
  37535. */
  37536. set: function (value) {
  37537. if (this._colorGradingBGR === value) {
  37538. return;
  37539. }
  37540. this._colorGradingBGR = value;
  37541. this._updateParameters();
  37542. },
  37543. enumerable: true,
  37544. configurable: true
  37545. });
  37546. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  37547. /**
  37548. * Gets the Exposure used in the effect.
  37549. */
  37550. get: function () {
  37551. return this._exposure;
  37552. },
  37553. /**
  37554. * Sets the Exposure used in the effect.
  37555. */
  37556. set: function (value) {
  37557. if (this._exposure === value) {
  37558. return;
  37559. }
  37560. this._exposure = value;
  37561. this._updateParameters();
  37562. },
  37563. enumerable: true,
  37564. configurable: true
  37565. });
  37566. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  37567. /**
  37568. * Gets wether the tone mapping effect is enabled.
  37569. */
  37570. get: function () {
  37571. return this._toneMappingEnabled;
  37572. },
  37573. /**
  37574. * Sets wether the tone mapping effect is enabled.
  37575. */
  37576. set: function (value) {
  37577. if (this._toneMappingEnabled === value) {
  37578. return;
  37579. }
  37580. this._toneMappingEnabled = value;
  37581. this._updateParameters();
  37582. },
  37583. enumerable: true,
  37584. configurable: true
  37585. });
  37586. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37587. /**
  37588. * Gets the contrast used in the effect.
  37589. */
  37590. get: function () {
  37591. return this._contrast;
  37592. },
  37593. /**
  37594. * Sets the contrast used in the effect.
  37595. */
  37596. set: function (value) {
  37597. if (this._contrast === value) {
  37598. return;
  37599. }
  37600. this._contrast = value;
  37601. this._updateParameters();
  37602. },
  37603. enumerable: true,
  37604. configurable: true
  37605. });
  37606. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainEnabled", {
  37607. /**
  37608. * If the grain effect should be enabled.
  37609. */
  37610. get: function () {
  37611. return this._grainEnabled;
  37612. },
  37613. set: function (value) {
  37614. if (this._grainEnabled === value) {
  37615. return;
  37616. }
  37617. this._grainEnabled = value;
  37618. this._updateParameters();
  37619. },
  37620. enumerable: true,
  37621. configurable: true
  37622. });
  37623. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainIntensity", {
  37624. /**
  37625. * Amount of grain to be applied by the grain effect.
  37626. */
  37627. get: function () {
  37628. return this._grainIntensity;
  37629. },
  37630. set: function (value) {
  37631. if (this._grainIntensity === value) {
  37632. return;
  37633. }
  37634. this._grainIntensity = value;
  37635. },
  37636. enumerable: true,
  37637. configurable: true
  37638. });
  37639. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainAnimated", {
  37640. /**
  37641. * If the grain effect should be animated.
  37642. */
  37643. get: function () {
  37644. return this._grainAnimated;
  37645. },
  37646. set: function (value) {
  37647. if (this._grainAnimated === value) {
  37648. return;
  37649. }
  37650. this._grainAnimated = value;
  37651. this._updateParameters();
  37652. },
  37653. enumerable: true,
  37654. configurable: true
  37655. });
  37656. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37657. /**
  37658. * Gets the vignette blend mode allowing different kind of effect.
  37659. */
  37660. get: function () {
  37661. return this._vignetteBlendMode;
  37662. },
  37663. /**
  37664. * Sets the vignette blend mode allowing different kind of effect.
  37665. */
  37666. set: function (value) {
  37667. if (this._vignetteBlendMode === value) {
  37668. return;
  37669. }
  37670. this._vignetteBlendMode = value;
  37671. this._updateParameters();
  37672. },
  37673. enumerable: true,
  37674. configurable: true
  37675. });
  37676. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37677. /**
  37678. * Gets wether the vignette effect is enabled.
  37679. */
  37680. get: function () {
  37681. return this._vignetteEnabled;
  37682. },
  37683. /**
  37684. * Sets wether the vignette effect is enabled.
  37685. */
  37686. set: function (value) {
  37687. if (this._vignetteEnabled === value) {
  37688. return;
  37689. }
  37690. this._vignetteEnabled = value;
  37691. this._updateParameters();
  37692. },
  37693. enumerable: true,
  37694. configurable: true
  37695. });
  37696. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37697. /**
  37698. * Gets wether the image processing is applied through a post process or not.
  37699. */
  37700. get: function () {
  37701. return this._applyByPostProcess;
  37702. },
  37703. /**
  37704. * Sets wether the image processing is applied through a post process or not.
  37705. */
  37706. set: function (value) {
  37707. if (this._applyByPostProcess === value) {
  37708. return;
  37709. }
  37710. this._applyByPostProcess = value;
  37711. this._updateParameters();
  37712. },
  37713. enumerable: true,
  37714. configurable: true
  37715. });
  37716. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37717. /**
  37718. * Gets wether the image processing is enabled or not.
  37719. */
  37720. get: function () {
  37721. return this._isEnabled;
  37722. },
  37723. /**
  37724. * Sets wether the image processing is enabled or not.
  37725. */
  37726. set: function (value) {
  37727. if (this._isEnabled === value) {
  37728. return;
  37729. }
  37730. this._isEnabled = value;
  37731. this._updateParameters();
  37732. },
  37733. enumerable: true,
  37734. configurable: true
  37735. });
  37736. /**
  37737. * Method called each time the image processing information changes requires to recompile the effect.
  37738. */
  37739. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37740. this.onUpdateParameters.notifyObservers(this);
  37741. };
  37742. ImageProcessingConfiguration.prototype.getClassName = function () {
  37743. return "ImageProcessingConfiguration";
  37744. };
  37745. /**
  37746. * Prepare the list of uniforms associated with the Image Processing effects.
  37747. * @param uniformsList The list of uniforms used in the effect
  37748. * @param defines the list of defines currently in use
  37749. */
  37750. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37751. if (defines.EXPOSURE) {
  37752. uniforms.push("exposureLinear");
  37753. }
  37754. if (defines.CONTRAST) {
  37755. uniforms.push("contrast");
  37756. }
  37757. if (defines.COLORGRADING) {
  37758. uniforms.push("colorTransformSettings");
  37759. }
  37760. if (defines.VIGNETTE) {
  37761. uniforms.push("vInverseScreenSize");
  37762. uniforms.push("vignetteSettings1");
  37763. uniforms.push("vignetteSettings2");
  37764. }
  37765. if (defines.COLORCURVES) {
  37766. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37767. }
  37768. if (defines.GRAIN) {
  37769. uniforms.push("grainVarianceAmount");
  37770. uniforms.push("grainAnimatedSeed");
  37771. }
  37772. };
  37773. /**
  37774. * Prepare the list of samplers associated with the Image Processing effects.
  37775. * @param uniformsList The list of uniforms used in the effect
  37776. * @param defines the list of defines currently in use
  37777. */
  37778. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37779. if (defines.COLORGRADING) {
  37780. samplersList.push("txColorTransform");
  37781. }
  37782. };
  37783. /**
  37784. * Prepare the list of defines associated to the shader.
  37785. * @param defines the list of defines to complete
  37786. */
  37787. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37788. if (forPostProcess === void 0) { forPostProcess = false; }
  37789. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37790. defines.VIGNETTE = false;
  37791. defines.TONEMAPPING = false;
  37792. defines.CONTRAST = false;
  37793. defines.EXPOSURE = false;
  37794. defines.COLORCURVES = false;
  37795. defines.COLORGRADING = false;
  37796. defines.COLORGRADING3D = false;
  37797. defines.IMAGEPROCESSING = false;
  37798. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37799. return;
  37800. }
  37801. defines.VIGNETTE = this.vignetteEnabled;
  37802. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37803. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37804. defines.TONEMAPPING = this.toneMappingEnabled;
  37805. defines.CONTRAST = (this.contrast !== 1.0);
  37806. defines.EXPOSURE = (this.exposure !== 1.0);
  37807. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37808. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37809. if (defines.COLORGRADING) {
  37810. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37811. }
  37812. else {
  37813. defines.COLORGRADING3D = false;
  37814. }
  37815. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37816. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37817. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37818. defines.GRAIN = this.grainEnabled;
  37819. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.GRAIN;
  37820. };
  37821. /**
  37822. * Returns true if all the image processing information are ready.
  37823. */
  37824. ImageProcessingConfiguration.prototype.isReady = function () {
  37825. // Color Grading texure can not be none blocking.
  37826. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37827. };
  37828. /**
  37829. * Binds the image processing to the shader.
  37830. * @param effect The effect to bind to
  37831. */
  37832. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37833. if (aspectRatio === void 0) { aspectRatio = 1; }
  37834. // Color Curves
  37835. if (this._colorCurvesEnabled && this.colorCurves) {
  37836. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37837. }
  37838. // Vignette
  37839. if (this._vignetteEnabled) {
  37840. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37841. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37842. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37843. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37844. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37845. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37846. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37847. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37848. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37849. var vignettePower = -2.0 * this.vignetteWeight;
  37850. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37851. }
  37852. // Exposure
  37853. effect.setFloat("exposureLinear", this.exposure);
  37854. // Contrast
  37855. effect.setFloat("contrast", this.contrast);
  37856. // Color transform settings
  37857. if (this.colorGradingTexture) {
  37858. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37859. var textureSize = this.colorGradingTexture.getSize().height;
  37860. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37861. 0.5 / textureSize, // textureOffset
  37862. textureSize, // textureSize
  37863. this.colorGradingTexture.level // weight
  37864. );
  37865. }
  37866. effect.setFloat("grainVarianceAmount", this.grainIntensity);
  37867. effect.setFloat("grainAnimatedSeed", this.grainAnimated ? Math.random() + 1 : 1);
  37868. };
  37869. /**
  37870. * Clones the current image processing instance.
  37871. * @return The cloned image processing
  37872. */
  37873. ImageProcessingConfiguration.prototype.clone = function () {
  37874. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37875. };
  37876. /**
  37877. * Serializes the current image processing instance to a json representation.
  37878. * @return a JSON representation
  37879. */
  37880. ImageProcessingConfiguration.prototype.serialize = function () {
  37881. return BABYLON.SerializationHelper.Serialize(this);
  37882. };
  37883. /**
  37884. * Parses the image processing from a json representation.
  37885. * @param source the JSON source to parse
  37886. * @return The parsed image processing
  37887. */
  37888. ImageProcessingConfiguration.Parse = function (source) {
  37889. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37890. };
  37891. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37892. /**
  37893. * Used to apply the vignette as a mix with the pixel color.
  37894. */
  37895. get: function () {
  37896. return this._VIGNETTEMODE_MULTIPLY;
  37897. },
  37898. enumerable: true,
  37899. configurable: true
  37900. });
  37901. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37902. /**
  37903. * Used to apply the vignette as a replacement of the pixel color.
  37904. */
  37905. get: function () {
  37906. return this._VIGNETTEMODE_OPAQUE;
  37907. },
  37908. enumerable: true,
  37909. configurable: true
  37910. });
  37911. // Static constants associated to the image processing.
  37912. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37913. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37914. __decorate([
  37915. BABYLON.serializeAsColorCurves()
  37916. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37917. __decorate([
  37918. BABYLON.serialize()
  37919. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37920. __decorate([
  37921. BABYLON.serializeAsTexture()
  37922. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37923. __decorate([
  37924. BABYLON.serialize()
  37925. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37926. __decorate([
  37927. BABYLON.serialize()
  37928. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37929. __decorate([
  37930. BABYLON.serialize()
  37931. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37932. __decorate([
  37933. BABYLON.serialize()
  37934. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37935. __decorate([
  37936. BABYLON.serialize()
  37937. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37938. __decorate([
  37939. BABYLON.serialize()
  37940. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  37941. __decorate([
  37942. BABYLON.serialize()
  37943. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  37944. __decorate([
  37945. BABYLON.serialize()
  37946. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  37947. __decorate([
  37948. BABYLON.serialize()
  37949. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  37950. __decorate([
  37951. BABYLON.serialize()
  37952. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  37953. __decorate([
  37954. BABYLON.serializeAsColor4()
  37955. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  37956. __decorate([
  37957. BABYLON.serialize()
  37958. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  37959. __decorate([
  37960. BABYLON.serialize()
  37961. ], ImageProcessingConfiguration.prototype, "_grainEnabled", void 0);
  37962. __decorate([
  37963. BABYLON.serialize()
  37964. ], ImageProcessingConfiguration.prototype, "_grainIntensity", void 0);
  37965. __decorate([
  37966. BABYLON.serialize()
  37967. ], ImageProcessingConfiguration.prototype, "_grainAnimated", void 0);
  37968. __decorate([
  37969. BABYLON.serialize()
  37970. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  37971. __decorate([
  37972. BABYLON.serialize()
  37973. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  37974. __decorate([
  37975. BABYLON.serialize()
  37976. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  37977. __decorate([
  37978. BABYLON.serialize()
  37979. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  37980. return ImageProcessingConfiguration;
  37981. }());
  37982. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  37983. })(BABYLON || (BABYLON = {}));
  37984. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  37985. "use strict";
  37986. var BABYLON;
  37987. (function (BABYLON) {
  37988. /**
  37989. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  37990. * It can help converting any input color in a desired output one. This can then be used to create effects
  37991. * from sepia, black and white to sixties or futuristic rendering...
  37992. *
  37993. * The only supported format is currently 3dl.
  37994. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  37995. */
  37996. var ColorGradingTexture = /** @class */ (function (_super) {
  37997. __extends(ColorGradingTexture, _super);
  37998. /**
  37999. * Instantiates a ColorGradingTexture from the following parameters.
  38000. *
  38001. * @param url The location of the color gradind data (currently only supporting 3dl)
  38002. * @param scene The scene the texture will be used in
  38003. */
  38004. function ColorGradingTexture(url, scene) {
  38005. var _this = _super.call(this, scene) || this;
  38006. if (!url) {
  38007. return _this;
  38008. }
  38009. _this._engine = scene.getEngine();
  38010. _this._textureMatrix = BABYLON.Matrix.Identity();
  38011. _this.name = url;
  38012. _this.url = url;
  38013. _this.hasAlpha = false;
  38014. _this.isCube = false;
  38015. _this.is3D = _this._engine.webGLVersion > 1;
  38016. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38017. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38018. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38019. _this.anisotropicFilteringLevel = 1;
  38020. _this._texture = _this._getFromCache(url, true);
  38021. if (!_this._texture) {
  38022. if (!scene.useDelayedTextureLoading) {
  38023. _this.loadTexture();
  38024. }
  38025. else {
  38026. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  38027. }
  38028. }
  38029. return _this;
  38030. }
  38031. /**
  38032. * Returns the texture matrix used in most of the material.
  38033. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  38034. */
  38035. ColorGradingTexture.prototype.getTextureMatrix = function () {
  38036. return this._textureMatrix;
  38037. };
  38038. /**
  38039. * Occurs when the file being loaded is a .3dl LUT file.
  38040. */
  38041. ColorGradingTexture.prototype.load3dlTexture = function () {
  38042. var engine = this._engine;
  38043. var texture;
  38044. if (engine.webGLVersion === 1) {
  38045. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38046. }
  38047. else {
  38048. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38049. }
  38050. this._texture = texture;
  38051. var callback = function (text) {
  38052. if (typeof text !== "string") {
  38053. return;
  38054. }
  38055. var data = null;
  38056. var tempData = null;
  38057. var line;
  38058. var lines = text.split('\n');
  38059. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  38060. var maxColor = 0;
  38061. for (var i = 0; i < lines.length; i++) {
  38062. line = lines[i];
  38063. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  38064. continue;
  38065. if (line.indexOf('#') === 0)
  38066. continue;
  38067. var words = line.split(" ");
  38068. if (size === 0) {
  38069. // Number of space + one
  38070. size = words.length;
  38071. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  38072. tempData = new Float32Array(size * size * size * 4);
  38073. continue;
  38074. }
  38075. if (size != 0) {
  38076. var r = Math.max(parseInt(words[0]), 0);
  38077. var g = Math.max(parseInt(words[1]), 0);
  38078. var b = Math.max(parseInt(words[2]), 0);
  38079. maxColor = Math.max(r, maxColor);
  38080. maxColor = Math.max(g, maxColor);
  38081. maxColor = Math.max(b, maxColor);
  38082. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  38083. if (tempData) {
  38084. tempData[pixelStorageIndex + 0] = r;
  38085. tempData[pixelStorageIndex + 1] = g;
  38086. tempData[pixelStorageIndex + 2] = b;
  38087. }
  38088. pixelIndexSlice++;
  38089. if (pixelIndexSlice % size == 0) {
  38090. pixelIndexH++;
  38091. pixelIndexSlice = 0;
  38092. if (pixelIndexH % size == 0) {
  38093. pixelIndexW++;
  38094. pixelIndexH = 0;
  38095. }
  38096. }
  38097. }
  38098. }
  38099. if (tempData && data) {
  38100. for (var i = 0; i < tempData.length; i++) {
  38101. if (i > 0 && (i + 1) % 4 === 0) {
  38102. data[i] = 255;
  38103. }
  38104. else {
  38105. var value = tempData[i];
  38106. data[i] = (value / maxColor * 255);
  38107. }
  38108. }
  38109. }
  38110. if (texture.is3D) {
  38111. texture.updateSize(size, size, size);
  38112. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38113. }
  38114. else {
  38115. texture.updateSize(size * size, size);
  38116. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38117. }
  38118. };
  38119. var scene = this.getScene();
  38120. if (scene) {
  38121. scene._loadFile(this.url, callback);
  38122. }
  38123. else {
  38124. this._engine._loadFile(this.url, callback);
  38125. }
  38126. return this._texture;
  38127. };
  38128. /**
  38129. * Starts the loading process of the texture.
  38130. */
  38131. ColorGradingTexture.prototype.loadTexture = function () {
  38132. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  38133. this.load3dlTexture();
  38134. }
  38135. };
  38136. /**
  38137. * Clones the color gradind texture.
  38138. */
  38139. ColorGradingTexture.prototype.clone = function () {
  38140. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  38141. // Base texture
  38142. newTexture.level = this.level;
  38143. return newTexture;
  38144. };
  38145. /**
  38146. * Called during delayed load for textures.
  38147. */
  38148. ColorGradingTexture.prototype.delayLoad = function () {
  38149. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  38150. return;
  38151. }
  38152. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38153. this._texture = this._getFromCache(this.url, true);
  38154. if (!this._texture) {
  38155. this.loadTexture();
  38156. }
  38157. };
  38158. /**
  38159. * Parses a color grading texture serialized by Babylon.
  38160. * @param parsedTexture The texture information being parsedTexture
  38161. * @param scene The scene to load the texture in
  38162. * @param rootUrl The root url of the data assets to load
  38163. * @return A color gradind texture
  38164. */
  38165. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  38166. var texture = null;
  38167. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  38168. texture = new ColorGradingTexture(parsedTexture.name, scene);
  38169. texture.name = parsedTexture.name;
  38170. texture.level = parsedTexture.level;
  38171. }
  38172. return texture;
  38173. };
  38174. /**
  38175. * Serializes the LUT texture to json format.
  38176. */
  38177. ColorGradingTexture.prototype.serialize = function () {
  38178. if (!this.name) {
  38179. return null;
  38180. }
  38181. var serializationObject = {};
  38182. serializationObject.name = this.name;
  38183. serializationObject.level = this.level;
  38184. serializationObject.customType = "BABYLON.ColorGradingTexture";
  38185. return serializationObject;
  38186. };
  38187. /**
  38188. * Empty line regex stored for GC.
  38189. */
  38190. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  38191. return ColorGradingTexture;
  38192. }(BABYLON.BaseTexture));
  38193. BABYLON.ColorGradingTexture = ColorGradingTexture;
  38194. })(BABYLON || (BABYLON = {}));
  38195. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  38196. "use strict";
  38197. var BABYLON;
  38198. (function (BABYLON) {
  38199. /**
  38200. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38201. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38202. * 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;
  38203. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38204. */
  38205. var ColorCurves = /** @class */ (function () {
  38206. function ColorCurves() {
  38207. this._dirty = true;
  38208. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  38209. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  38210. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38211. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  38212. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38213. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  38214. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  38215. this._globalHue = 30;
  38216. this._globalDensity = 0;
  38217. this._globalSaturation = 0;
  38218. this._globalExposure = 0;
  38219. this._highlightsHue = 30;
  38220. this._highlightsDensity = 0;
  38221. this._highlightsSaturation = 0;
  38222. this._highlightsExposure = 0;
  38223. this._midtonesHue = 30;
  38224. this._midtonesDensity = 0;
  38225. this._midtonesSaturation = 0;
  38226. this._midtonesExposure = 0;
  38227. this._shadowsHue = 30;
  38228. this._shadowsDensity = 0;
  38229. this._shadowsSaturation = 0;
  38230. this._shadowsExposure = 0;
  38231. }
  38232. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  38233. /**
  38234. * Gets the global Hue value.
  38235. * 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).
  38236. */
  38237. get: function () {
  38238. return this._globalHue;
  38239. },
  38240. /**
  38241. * Sets the global Hue value.
  38242. * 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).
  38243. */
  38244. set: function (value) {
  38245. this._globalHue = value;
  38246. this._dirty = true;
  38247. },
  38248. enumerable: true,
  38249. configurable: true
  38250. });
  38251. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  38252. /**
  38253. * Gets the global Density value.
  38254. * 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.
  38255. * Values less than zero provide a filter of opposite hue.
  38256. */
  38257. get: function () {
  38258. return this._globalDensity;
  38259. },
  38260. /**
  38261. * Sets the global Density value.
  38262. * 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.
  38263. * Values less than zero provide a filter of opposite hue.
  38264. */
  38265. set: function (value) {
  38266. this._globalDensity = value;
  38267. this._dirty = true;
  38268. },
  38269. enumerable: true,
  38270. configurable: true
  38271. });
  38272. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  38273. /**
  38274. * Gets the global Saturation value.
  38275. * 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.
  38276. */
  38277. get: function () {
  38278. return this._globalSaturation;
  38279. },
  38280. /**
  38281. * Sets the global Saturation value.
  38282. * 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.
  38283. */
  38284. set: function (value) {
  38285. this._globalSaturation = value;
  38286. this._dirty = true;
  38287. },
  38288. enumerable: true,
  38289. configurable: true
  38290. });
  38291. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  38292. /**
  38293. * Gets the highlights Hue value.
  38294. * 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).
  38295. */
  38296. get: function () {
  38297. return this._highlightsHue;
  38298. },
  38299. /**
  38300. * Sets the highlights Hue value.
  38301. * 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).
  38302. */
  38303. set: function (value) {
  38304. this._highlightsHue = value;
  38305. this._dirty = true;
  38306. },
  38307. enumerable: true,
  38308. configurable: true
  38309. });
  38310. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  38311. /**
  38312. * Gets the highlights Density value.
  38313. * 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.
  38314. * Values less than zero provide a filter of opposite hue.
  38315. */
  38316. get: function () {
  38317. return this._highlightsDensity;
  38318. },
  38319. /**
  38320. * Sets the highlights Density value.
  38321. * 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.
  38322. * Values less than zero provide a filter of opposite hue.
  38323. */
  38324. set: function (value) {
  38325. this._highlightsDensity = value;
  38326. this._dirty = true;
  38327. },
  38328. enumerable: true,
  38329. configurable: true
  38330. });
  38331. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  38332. /**
  38333. * Gets the highlights Saturation value.
  38334. * 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.
  38335. */
  38336. get: function () {
  38337. return this._highlightsSaturation;
  38338. },
  38339. /**
  38340. * Sets the highlights Saturation value.
  38341. * 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.
  38342. */
  38343. set: function (value) {
  38344. this._highlightsSaturation = value;
  38345. this._dirty = true;
  38346. },
  38347. enumerable: true,
  38348. configurable: true
  38349. });
  38350. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  38351. /**
  38352. * Gets the highlights Exposure value.
  38353. * 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.
  38354. */
  38355. get: function () {
  38356. return this._highlightsExposure;
  38357. },
  38358. /**
  38359. * Sets the highlights Exposure value.
  38360. * 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.
  38361. */
  38362. set: function (value) {
  38363. this._highlightsExposure = value;
  38364. this._dirty = true;
  38365. },
  38366. enumerable: true,
  38367. configurable: true
  38368. });
  38369. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  38370. /**
  38371. * Gets the midtones Hue value.
  38372. * 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).
  38373. */
  38374. get: function () {
  38375. return this._midtonesHue;
  38376. },
  38377. /**
  38378. * Sets the midtones Hue value.
  38379. * 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).
  38380. */
  38381. set: function (value) {
  38382. this._midtonesHue = value;
  38383. this._dirty = true;
  38384. },
  38385. enumerable: true,
  38386. configurable: true
  38387. });
  38388. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  38389. /**
  38390. * Gets the midtones Density value.
  38391. * 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.
  38392. * Values less than zero provide a filter of opposite hue.
  38393. */
  38394. get: function () {
  38395. return this._midtonesDensity;
  38396. },
  38397. /**
  38398. * Sets the midtones Density value.
  38399. * 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.
  38400. * Values less than zero provide a filter of opposite hue.
  38401. */
  38402. set: function (value) {
  38403. this._midtonesDensity = value;
  38404. this._dirty = true;
  38405. },
  38406. enumerable: true,
  38407. configurable: true
  38408. });
  38409. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  38410. /**
  38411. * Gets the midtones Saturation value.
  38412. * 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.
  38413. */
  38414. get: function () {
  38415. return this._midtonesSaturation;
  38416. },
  38417. /**
  38418. * Sets the midtones Saturation value.
  38419. * 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.
  38420. */
  38421. set: function (value) {
  38422. this._midtonesSaturation = value;
  38423. this._dirty = true;
  38424. },
  38425. enumerable: true,
  38426. configurable: true
  38427. });
  38428. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  38429. /**
  38430. * Gets the midtones Exposure value.
  38431. * 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.
  38432. */
  38433. get: function () {
  38434. return this._midtonesExposure;
  38435. },
  38436. /**
  38437. * Sets the midtones Exposure value.
  38438. * 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.
  38439. */
  38440. set: function (value) {
  38441. this._midtonesExposure = value;
  38442. this._dirty = true;
  38443. },
  38444. enumerable: true,
  38445. configurable: true
  38446. });
  38447. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  38448. /**
  38449. * Gets the shadows Hue value.
  38450. * 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).
  38451. */
  38452. get: function () {
  38453. return this._shadowsHue;
  38454. },
  38455. /**
  38456. * Sets the shadows Hue value.
  38457. * 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).
  38458. */
  38459. set: function (value) {
  38460. this._shadowsHue = value;
  38461. this._dirty = true;
  38462. },
  38463. enumerable: true,
  38464. configurable: true
  38465. });
  38466. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  38467. /**
  38468. * Gets the shadows Density value.
  38469. * 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.
  38470. * Values less than zero provide a filter of opposite hue.
  38471. */
  38472. get: function () {
  38473. return this._shadowsDensity;
  38474. },
  38475. /**
  38476. * Sets the shadows Density value.
  38477. * 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.
  38478. * Values less than zero provide a filter of opposite hue.
  38479. */
  38480. set: function (value) {
  38481. this._shadowsDensity = value;
  38482. this._dirty = true;
  38483. },
  38484. enumerable: true,
  38485. configurable: true
  38486. });
  38487. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  38488. /**
  38489. * Gets the shadows Saturation value.
  38490. * 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.
  38491. */
  38492. get: function () {
  38493. return this._shadowsSaturation;
  38494. },
  38495. /**
  38496. * Sets the shadows Saturation value.
  38497. * 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.
  38498. */
  38499. set: function (value) {
  38500. this._shadowsSaturation = value;
  38501. this._dirty = true;
  38502. },
  38503. enumerable: true,
  38504. configurable: true
  38505. });
  38506. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  38507. /**
  38508. * Gets the shadows Exposure value.
  38509. * 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.
  38510. */
  38511. get: function () {
  38512. return this._shadowsExposure;
  38513. },
  38514. /**
  38515. * Sets the shadows Exposure value.
  38516. * 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.
  38517. */
  38518. set: function (value) {
  38519. this._shadowsExposure = value;
  38520. this._dirty = true;
  38521. },
  38522. enumerable: true,
  38523. configurable: true
  38524. });
  38525. ColorCurves.prototype.getClassName = function () {
  38526. return "ColorCurves";
  38527. };
  38528. /**
  38529. * Binds the color curves to the shader.
  38530. * @param colorCurves The color curve to bind
  38531. * @param effect The effect to bind to
  38532. */
  38533. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  38534. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  38535. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  38536. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  38537. if (colorCurves._dirty) {
  38538. colorCurves._dirty = false;
  38539. // Fill in global info.
  38540. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  38541. // Compute highlights info.
  38542. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  38543. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  38544. // Compute midtones info.
  38545. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  38546. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  38547. // Compute shadows info.
  38548. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  38549. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  38550. // Compute deltas (neutral is midtones).
  38551. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  38552. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  38553. }
  38554. if (effect) {
  38555. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  38556. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  38557. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  38558. }
  38559. };
  38560. /**
  38561. * Prepare the list of uniforms associated with the ColorCurves effects.
  38562. * @param uniformsList The list of uniforms used in the effect
  38563. */
  38564. ColorCurves.PrepareUniforms = function (uniformsList) {
  38565. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  38566. };
  38567. /**
  38568. * Returns color grading data based on a hue, density, saturation and exposure value.
  38569. * @param filterHue The hue of the color filter.
  38570. * @param filterDensity The density of the color filter.
  38571. * @param saturation The saturation.
  38572. * @param exposure The exposure.
  38573. * @param result The result data container.
  38574. */
  38575. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  38576. if (hue == null) {
  38577. return;
  38578. }
  38579. hue = ColorCurves.clamp(hue, 0, 360);
  38580. density = ColorCurves.clamp(density, -100, 100);
  38581. saturation = ColorCurves.clamp(saturation, -100, 100);
  38582. exposure = ColorCurves.clamp(exposure, -100, 100);
  38583. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38584. // so that the maximum filter density is only 50% control. This provides fine control
  38585. // for small values and reasonable range.
  38586. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38587. density *= 0.5;
  38588. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38589. if (density < 0) {
  38590. density *= -1;
  38591. hue = (hue + 180) % 360;
  38592. }
  38593. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38594. result.scaleToRef(2, result);
  38595. result.a = 1 + 0.01 * saturation;
  38596. };
  38597. /**
  38598. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38599. * @param value The input slider value in range [-100,100].
  38600. * @returns Adjusted value.
  38601. */
  38602. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38603. value /= 100;
  38604. var x = Math.abs(value);
  38605. x = Math.pow(x, 2);
  38606. if (value < 0) {
  38607. x *= -1;
  38608. }
  38609. x *= 100;
  38610. return x;
  38611. };
  38612. /**
  38613. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38614. * @param hue The hue (H) input.
  38615. * @param saturation The saturation (S) input.
  38616. * @param brightness The brightness (B) input.
  38617. * @result An RGBA color represented as Vector4.
  38618. */
  38619. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38620. var h = ColorCurves.clamp(hue, 0, 360);
  38621. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38622. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38623. if (s === 0) {
  38624. result.r = v;
  38625. result.g = v;
  38626. result.b = v;
  38627. }
  38628. else {
  38629. // sector 0 to 5
  38630. h /= 60;
  38631. var i = Math.floor(h);
  38632. // fractional part of h
  38633. var f = h - i;
  38634. var p = v * (1 - s);
  38635. var q = v * (1 - s * f);
  38636. var t = v * (1 - s * (1 - f));
  38637. switch (i) {
  38638. case 0:
  38639. result.r = v;
  38640. result.g = t;
  38641. result.b = p;
  38642. break;
  38643. case 1:
  38644. result.r = q;
  38645. result.g = v;
  38646. result.b = p;
  38647. break;
  38648. case 2:
  38649. result.r = p;
  38650. result.g = v;
  38651. result.b = t;
  38652. break;
  38653. case 3:
  38654. result.r = p;
  38655. result.g = q;
  38656. result.b = v;
  38657. break;
  38658. case 4:
  38659. result.r = t;
  38660. result.g = p;
  38661. result.b = v;
  38662. break;
  38663. default:// case 5:
  38664. result.r = v;
  38665. result.g = p;
  38666. result.b = q;
  38667. break;
  38668. }
  38669. }
  38670. result.a = 1;
  38671. };
  38672. /**
  38673. * Returns a value clamped between min and max
  38674. * @param value The value to clamp
  38675. * @param min The minimum of value
  38676. * @param max The maximum of value
  38677. * @returns The clamped value.
  38678. */
  38679. ColorCurves.clamp = function (value, min, max) {
  38680. return Math.min(Math.max(value, min), max);
  38681. };
  38682. /**
  38683. * Clones the current color curve instance.
  38684. * @return The cloned curves
  38685. */
  38686. ColorCurves.prototype.clone = function () {
  38687. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38688. };
  38689. /**
  38690. * Serializes the current color curve instance to a json representation.
  38691. * @return a JSON representation
  38692. */
  38693. ColorCurves.prototype.serialize = function () {
  38694. return BABYLON.SerializationHelper.Serialize(this);
  38695. };
  38696. /**
  38697. * Parses the color curve from a json representation.
  38698. * @param source the JSON source to parse
  38699. * @return The parsed curves
  38700. */
  38701. ColorCurves.Parse = function (source) {
  38702. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38703. };
  38704. __decorate([
  38705. BABYLON.serialize()
  38706. ], ColorCurves.prototype, "_globalHue", void 0);
  38707. __decorate([
  38708. BABYLON.serialize()
  38709. ], ColorCurves.prototype, "_globalDensity", void 0);
  38710. __decorate([
  38711. BABYLON.serialize()
  38712. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38713. __decorate([
  38714. BABYLON.serialize()
  38715. ], ColorCurves.prototype, "_globalExposure", void 0);
  38716. __decorate([
  38717. BABYLON.serialize()
  38718. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38719. __decorate([
  38720. BABYLON.serialize()
  38721. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38722. __decorate([
  38723. BABYLON.serialize()
  38724. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38725. __decorate([
  38726. BABYLON.serialize()
  38727. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38728. __decorate([
  38729. BABYLON.serialize()
  38730. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38731. __decorate([
  38732. BABYLON.serialize()
  38733. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38734. __decorate([
  38735. BABYLON.serialize()
  38736. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38737. __decorate([
  38738. BABYLON.serialize()
  38739. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38740. return ColorCurves;
  38741. }());
  38742. BABYLON.ColorCurves = ColorCurves;
  38743. })(BABYLON || (BABYLON = {}));
  38744. //# sourceMappingURL=babylon.colorCurves.js.map
  38745. "use strict";
  38746. //# sourceMappingURL=babylon.behavior.js.map
  38747. "use strict";
  38748. var BABYLON;
  38749. (function (BABYLON) {
  38750. /**
  38751. * "Static Class" containing the most commonly used helper while dealing with material for
  38752. * rendering purpose.
  38753. *
  38754. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38755. *
  38756. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38757. */
  38758. var MaterialHelper = /** @class */ (function () {
  38759. function MaterialHelper() {
  38760. }
  38761. /**
  38762. * Bind the current view position to an effect.
  38763. * @param effect The effect to be bound
  38764. * @param scene The scene the eyes position is used from
  38765. */
  38766. MaterialHelper.BindEyePosition = function (effect, scene) {
  38767. if (scene._forcedViewPosition) {
  38768. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38769. return;
  38770. }
  38771. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38772. };
  38773. /**
  38774. * Helps preparing the defines values about the UVs in used in the effect.
  38775. * UVs are shared as much as we can accross chanels in the shaders.
  38776. * @param texture The texture we are preparing the UVs for
  38777. * @param defines The defines to update
  38778. * @param key The chanel key "diffuse", "specular"... used in the shader
  38779. */
  38780. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38781. defines._needUVs = true;
  38782. defines[key] = true;
  38783. if (texture.getTextureMatrix().isIdentity(true)) {
  38784. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38785. if (texture.coordinatesIndex === 0) {
  38786. defines["MAINUV1"] = true;
  38787. }
  38788. else {
  38789. defines["MAINUV2"] = true;
  38790. }
  38791. }
  38792. else {
  38793. defines[key + "DIRECTUV"] = 0;
  38794. }
  38795. };
  38796. /**
  38797. * Binds a texture matrix value to its corrsponding uniform
  38798. * @param texture The texture to bind the matrix for
  38799. * @param uniformBuffer The uniform buffer receivin the data
  38800. * @param key The chanel key "diffuse", "specular"... used in the shader
  38801. */
  38802. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38803. var matrix = texture.getTextureMatrix();
  38804. if (!matrix.isIdentity(true)) {
  38805. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38806. }
  38807. };
  38808. /**
  38809. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38810. * @param mesh defines the current mesh
  38811. * @param scene defines the current scene
  38812. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38813. * @param pointsCloud defines if point cloud rendering has to be turned on
  38814. * @param fogEnabled defines if fog has to be turned on
  38815. * @param alphaTest defines if alpha testing has to be turned on
  38816. * @param defines defines the current list of defines
  38817. */
  38818. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38819. if (defines._areMiscDirty) {
  38820. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38821. defines["POINTSIZE"] = pointsCloud;
  38822. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38823. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38824. defines["ALPHATEST"] = alphaTest;
  38825. }
  38826. };
  38827. /**
  38828. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38829. * @param scene defines the current scene
  38830. * @param engine defines the current engine
  38831. * @param defines specifies the list of active defines
  38832. * @param useInstances defines if instances have to be turned on
  38833. * @param useClipPlane defines if clip plane have to be turned on
  38834. */
  38835. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38836. if (useClipPlane === void 0) { useClipPlane = null; }
  38837. var changed = false;
  38838. if (useClipPlane == null) {
  38839. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38840. }
  38841. if (defines["CLIPPLANE"] !== useClipPlane) {
  38842. defines["CLIPPLANE"] = useClipPlane;
  38843. changed = true;
  38844. }
  38845. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38846. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38847. changed = true;
  38848. }
  38849. if (defines["INSTANCES"] !== useInstances) {
  38850. defines["INSTANCES"] = useInstances;
  38851. changed = true;
  38852. }
  38853. if (changed) {
  38854. defines.markAsUnprocessed();
  38855. }
  38856. };
  38857. /**
  38858. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38859. * @param mesh The mesh containing the geometry data we will draw
  38860. * @param defines The defines to update
  38861. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38862. * @param useBones Precise whether bones should be used or not (override mesh info)
  38863. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38864. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38865. * @returns false if defines are considered not dirty and have not been checked
  38866. */
  38867. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38868. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38869. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38870. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38871. return false;
  38872. }
  38873. defines._normals = defines._needNormals;
  38874. defines._uvs = defines._needUVs;
  38875. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38876. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38877. defines["TANGENT"] = true;
  38878. }
  38879. if (defines._needUVs) {
  38880. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38881. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38882. }
  38883. else {
  38884. defines["UV1"] = false;
  38885. defines["UV2"] = false;
  38886. }
  38887. if (useVertexColor) {
  38888. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38889. defines["VERTEXCOLOR"] = hasVertexColors;
  38890. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38891. }
  38892. if (useBones) {
  38893. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38894. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38895. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38896. }
  38897. else {
  38898. defines["NUM_BONE_INFLUENCERS"] = 0;
  38899. defines["BonesPerMesh"] = 0;
  38900. }
  38901. }
  38902. if (useMorphTargets) {
  38903. var manager = mesh.morphTargetManager;
  38904. if (manager) {
  38905. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38906. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38907. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38908. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38909. }
  38910. else {
  38911. defines["MORPHTARGETS_TANGENT"] = false;
  38912. defines["MORPHTARGETS_NORMAL"] = false;
  38913. defines["MORPHTARGETS"] = false;
  38914. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38915. }
  38916. }
  38917. return true;
  38918. };
  38919. /**
  38920. * Prepares the defines related to the light information passed in parameter
  38921. * @param scene The scene we are intending to draw
  38922. * @param mesh The mesh the effect is compiling for
  38923. * @param defines The defines to update
  38924. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38925. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38926. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38927. * @returns true if normals will be required for the rest of the effect
  38928. */
  38929. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38930. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38931. if (disableLighting === void 0) { disableLighting = false; }
  38932. if (!defines._areLightsDirty) {
  38933. return defines._needNormals;
  38934. }
  38935. var lightIndex = 0;
  38936. var needNormals = false;
  38937. var needRebuild = false;
  38938. var lightmapMode = false;
  38939. var shadowEnabled = false;
  38940. var specularEnabled = false;
  38941. if (scene.lightsEnabled && !disableLighting) {
  38942. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38943. var light = _a[_i];
  38944. needNormals = true;
  38945. if (defines["LIGHT" + lightIndex] === undefined) {
  38946. needRebuild = true;
  38947. }
  38948. defines["LIGHT" + lightIndex] = true;
  38949. defines["SPOTLIGHT" + lightIndex] = false;
  38950. defines["HEMILIGHT" + lightIndex] = false;
  38951. defines["POINTLIGHT" + lightIndex] = false;
  38952. defines["DIRLIGHT" + lightIndex] = false;
  38953. var type;
  38954. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  38955. type = "SPOTLIGHT" + lightIndex;
  38956. var spotLight = light;
  38957. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  38958. }
  38959. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  38960. type = "HEMILIGHT" + lightIndex;
  38961. }
  38962. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  38963. type = "POINTLIGHT" + lightIndex;
  38964. }
  38965. else {
  38966. type = "DIRLIGHT" + lightIndex;
  38967. }
  38968. defines[type] = true;
  38969. // Specular
  38970. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  38971. specularEnabled = true;
  38972. }
  38973. // Shadows
  38974. defines["SHADOW" + lightIndex] = false;
  38975. defines["SHADOWPCF" + lightIndex] = false;
  38976. defines["SHADOWPCSS" + lightIndex] = false;
  38977. defines["SHADOWPOISSON" + lightIndex] = false;
  38978. defines["SHADOWESM" + lightIndex] = false;
  38979. defines["SHADOWCUBE" + lightIndex] = false;
  38980. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  38981. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  38982. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  38983. var shadowGenerator = light.getShadowGenerator();
  38984. if (shadowGenerator) {
  38985. shadowEnabled = true;
  38986. shadowGenerator.prepareDefines(defines, lightIndex);
  38987. }
  38988. }
  38989. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  38990. lightmapMode = true;
  38991. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  38992. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  38993. }
  38994. else {
  38995. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  38996. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  38997. }
  38998. lightIndex++;
  38999. if (lightIndex === maxSimultaneousLights)
  39000. break;
  39001. }
  39002. }
  39003. defines["SPECULARTERM"] = specularEnabled;
  39004. defines["SHADOWS"] = shadowEnabled;
  39005. // Resetting all other lights if any
  39006. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  39007. if (defines["LIGHT" + index] !== undefined) {
  39008. defines["LIGHT" + index] = false;
  39009. defines["HEMILIGHT" + lightIndex] = false;
  39010. defines["POINTLIGHT" + lightIndex] = false;
  39011. defines["DIRLIGHT" + lightIndex] = false;
  39012. defines["SPOTLIGHT" + lightIndex] = false;
  39013. defines["SHADOW" + lightIndex] = false;
  39014. }
  39015. }
  39016. var caps = scene.getEngine().getCaps();
  39017. if (defines["SHADOWFLOAT"] === undefined) {
  39018. needRebuild = true;
  39019. }
  39020. defines["SHADOWFLOAT"] = shadowEnabled &&
  39021. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  39022. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  39023. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  39024. if (needRebuild) {
  39025. defines.rebuild();
  39026. }
  39027. return needNormals;
  39028. };
  39029. /**
  39030. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  39031. * that won t be acctive due to defines being turned off.
  39032. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  39033. * @param samplersList The samplers list
  39034. * @param defines The defines helping in the list generation
  39035. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  39036. */
  39037. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  39038. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39039. var uniformsList;
  39040. var uniformBuffersList = null;
  39041. if (uniformsListOrOptions.uniformsNames) {
  39042. var options = uniformsListOrOptions;
  39043. uniformsList = options.uniformsNames;
  39044. uniformBuffersList = options.uniformBuffersNames;
  39045. samplersList = options.samplers;
  39046. defines = options.defines;
  39047. maxSimultaneousLights = options.maxSimultaneousLights;
  39048. }
  39049. else {
  39050. uniformsList = uniformsListOrOptions;
  39051. if (!samplersList) {
  39052. samplersList = [];
  39053. }
  39054. }
  39055. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39056. if (!defines["LIGHT" + lightIndex]) {
  39057. break;
  39058. }
  39059. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  39060. if (uniformBuffersList) {
  39061. uniformBuffersList.push("Light" + lightIndex);
  39062. }
  39063. samplersList.push("shadowSampler" + lightIndex);
  39064. samplersList.push("depthSampler" + lightIndex);
  39065. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  39066. samplersList.push("projectionLightSampler" + lightIndex);
  39067. uniformsList.push("textureProjectionMatrix" + lightIndex);
  39068. }
  39069. }
  39070. if (defines["NUM_MORPH_INFLUENCERS"]) {
  39071. uniformsList.push("morphTargetInfluences");
  39072. }
  39073. };
  39074. /**
  39075. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  39076. * @param defines The defines to update while falling back
  39077. * @param fallbacks The authorized effect fallbacks
  39078. * @param maxSimultaneousLights The maximum number of lights allowed
  39079. * @param rank the current rank of the Effect
  39080. * @returns The newly affected rank
  39081. */
  39082. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  39083. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39084. if (rank === void 0) { rank = 0; }
  39085. var lightFallbackRank = 0;
  39086. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39087. if (!defines["LIGHT" + lightIndex]) {
  39088. break;
  39089. }
  39090. if (lightIndex > 0) {
  39091. lightFallbackRank = rank + lightIndex;
  39092. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  39093. }
  39094. if (!defines["SHADOWS"]) {
  39095. if (defines["SHADOW" + lightIndex]) {
  39096. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  39097. }
  39098. if (defines["SHADOWPCF" + lightIndex]) {
  39099. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  39100. }
  39101. if (defines["SHADOWPCSS" + lightIndex]) {
  39102. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  39103. }
  39104. if (defines["SHADOWPOISSON" + lightIndex]) {
  39105. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  39106. }
  39107. if (defines["SHADOWESM" + lightIndex]) {
  39108. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  39109. }
  39110. }
  39111. }
  39112. return lightFallbackRank++;
  39113. };
  39114. /**
  39115. * Prepares the list of attributes required for morph targets according to the effect defines.
  39116. * @param attribs The current list of supported attribs
  39117. * @param mesh The mesh to prepare the morph targets attributes for
  39118. * @param defines The current Defines of the effect
  39119. */
  39120. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  39121. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  39122. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  39123. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  39124. var manager = mesh.morphTargetManager;
  39125. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  39126. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  39127. for (var index = 0; index < influencers; index++) {
  39128. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  39129. if (normal) {
  39130. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  39131. }
  39132. if (tangent) {
  39133. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  39134. }
  39135. if (attribs.length > maxAttributesCount) {
  39136. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  39137. }
  39138. }
  39139. }
  39140. };
  39141. /**
  39142. * Prepares the list of attributes required for bones according to the effect defines.
  39143. * @param attribs The current list of supported attribs
  39144. * @param mesh The mesh to prepare the bones attributes for
  39145. * @param defines The current Defines of the effect
  39146. * @param fallbacks The current efffect fallback strategy
  39147. */
  39148. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  39149. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  39150. fallbacks.addCPUSkinningFallback(0, mesh);
  39151. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39152. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39153. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  39154. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39155. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39156. }
  39157. }
  39158. };
  39159. /**
  39160. * Prepares the list of attributes required for instances according to the effect defines.
  39161. * @param attribs The current list of supported attribs
  39162. * @param defines The current Defines of the effect
  39163. */
  39164. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  39165. if (defines["INSTANCES"]) {
  39166. attribs.push("world0");
  39167. attribs.push("world1");
  39168. attribs.push("world2");
  39169. attribs.push("world3");
  39170. }
  39171. };
  39172. /**
  39173. * Binds the light shadow information to the effect for the given mesh.
  39174. * @param light The light containing the generator
  39175. * @param scene The scene the lights belongs to
  39176. * @param mesh The mesh we are binding the information to render
  39177. * @param lightIndex The light index in the effect used to render the mesh
  39178. * @param effect The effect we are binding the data to
  39179. */
  39180. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  39181. if (light.shadowEnabled && mesh.receiveShadows) {
  39182. var shadowGenerator = light.getShadowGenerator();
  39183. if (shadowGenerator) {
  39184. shadowGenerator.bindShadowLight(lightIndex, effect);
  39185. }
  39186. }
  39187. };
  39188. /**
  39189. * Binds the light information to the effect.
  39190. * @param light The light containing the generator
  39191. * @param effect The effect we are binding the data to
  39192. * @param lightIndex The light index in the effect used to render
  39193. */
  39194. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  39195. light.transferToEffect(effect, lightIndex + "");
  39196. };
  39197. /**
  39198. * Binds the lights information from the scene to the effect for the given mesh.
  39199. * @param scene The scene the lights belongs to
  39200. * @param mesh The mesh we are binding the information to render
  39201. * @param effect The effect we are binding the data to
  39202. * @param defines The generated defines for the effect
  39203. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  39204. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  39205. */
  39206. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  39207. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39208. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  39209. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  39210. for (var i = 0; i < len; i++) {
  39211. var light = mesh._lightSources[i];
  39212. var iAsString = i.toString();
  39213. var scaledIntensity = light.getScaledIntensity();
  39214. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  39215. MaterialHelper.BindLightProperties(light, effect, i);
  39216. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  39217. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  39218. if (defines["SPECULARTERM"]) {
  39219. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  39220. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  39221. }
  39222. // Shadows
  39223. if (scene.shadowsEnabled) {
  39224. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  39225. }
  39226. light._uniformBuffer.update();
  39227. }
  39228. };
  39229. /**
  39230. * Binds the fog information from the scene to the effect for the given mesh.
  39231. * @param scene The scene the lights belongs to
  39232. * @param mesh The mesh we are binding the information to render
  39233. * @param effect The effect we are binding the data to
  39234. */
  39235. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  39236. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  39237. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  39238. effect.setColor3("vFogColor", scene.fogColor);
  39239. }
  39240. };
  39241. /**
  39242. * Binds the bones information from the mesh to the effect.
  39243. * @param mesh The mesh we are binding the information to render
  39244. * @param effect The effect we are binding the data to
  39245. */
  39246. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  39247. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  39248. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  39249. if (matrices && effect) {
  39250. effect.setMatrices("mBones", matrices);
  39251. }
  39252. }
  39253. };
  39254. /**
  39255. * Binds the morph targets information from the mesh to the effect.
  39256. * @param abstractMesh The mesh we are binding the information to render
  39257. * @param effect The effect we are binding the data to
  39258. */
  39259. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  39260. var manager = abstractMesh.morphTargetManager;
  39261. if (!abstractMesh || !manager) {
  39262. return;
  39263. }
  39264. effect.setFloatArray("morphTargetInfluences", manager.influences);
  39265. };
  39266. /**
  39267. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  39268. * @param defines The generated defines used in the effect
  39269. * @param effect The effect we are binding the data to
  39270. * @param scene The scene we are willing to render with logarithmic scale for
  39271. */
  39272. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  39273. if (defines["LOGARITHMICDEPTH"]) {
  39274. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  39275. }
  39276. };
  39277. /**
  39278. * Binds the clip plane information from the scene to the effect.
  39279. * @param scene The scene the clip plane information are extracted from
  39280. * @param effect The effect we are binding the data to
  39281. */
  39282. MaterialHelper.BindClipPlane = function (effect, scene) {
  39283. if (scene.clipPlane) {
  39284. var clipPlane = scene.clipPlane;
  39285. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  39286. }
  39287. };
  39288. return MaterialHelper;
  39289. }());
  39290. BABYLON.MaterialHelper = MaterialHelper;
  39291. })(BABYLON || (BABYLON = {}));
  39292. //# sourceMappingURL=babylon.materialHelper.js.map
  39293. "use strict";
  39294. var BABYLON;
  39295. (function (BABYLON) {
  39296. var PushMaterial = /** @class */ (function (_super) {
  39297. __extends(PushMaterial, _super);
  39298. function PushMaterial(name, scene) {
  39299. var _this = _super.call(this, name, scene) || this;
  39300. _this._normalMatrix = new BABYLON.Matrix();
  39301. _this.storeEffectOnSubMeshes = true;
  39302. return _this;
  39303. }
  39304. PushMaterial.prototype.getEffect = function () {
  39305. return this._activeEffect;
  39306. };
  39307. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  39308. if (!mesh) {
  39309. return false;
  39310. }
  39311. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  39312. return true;
  39313. }
  39314. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  39315. };
  39316. /**
  39317. * Binds the given world matrix to the active effect
  39318. *
  39319. * @param world the matrix to bind
  39320. */
  39321. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39322. this._activeEffect.setMatrix("world", world);
  39323. };
  39324. /**
  39325. * Binds the given normal matrix to the active effect
  39326. *
  39327. * @param normalMatrix the matrix to bind
  39328. */
  39329. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  39330. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  39331. };
  39332. PushMaterial.prototype.bind = function (world, mesh) {
  39333. if (!mesh) {
  39334. return;
  39335. }
  39336. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  39337. };
  39338. PushMaterial.prototype._afterBind = function (mesh, effect) {
  39339. if (effect === void 0) { effect = null; }
  39340. _super.prototype._afterBind.call(this, mesh);
  39341. this.getScene()._cachedEffect = effect;
  39342. };
  39343. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  39344. if (visibility === void 0) { visibility = 1; }
  39345. return scene.isCachedMaterialInvalid(this, effect, visibility);
  39346. };
  39347. return PushMaterial;
  39348. }(BABYLON.Material));
  39349. BABYLON.PushMaterial = PushMaterial;
  39350. })(BABYLON || (BABYLON = {}));
  39351. //# sourceMappingURL=babylon.pushMaterial.js.map
  39352. "use strict";
  39353. var BABYLON;
  39354. (function (BABYLON) {
  39355. /** @ignore */
  39356. var StandardMaterialDefines = /** @class */ (function (_super) {
  39357. __extends(StandardMaterialDefines, _super);
  39358. function StandardMaterialDefines() {
  39359. var _this = _super.call(this) || this;
  39360. _this.MAINUV1 = false;
  39361. _this.MAINUV2 = false;
  39362. _this.DIFFUSE = false;
  39363. _this.DIFFUSEDIRECTUV = 0;
  39364. _this.AMBIENT = false;
  39365. _this.AMBIENTDIRECTUV = 0;
  39366. _this.OPACITY = false;
  39367. _this.OPACITYDIRECTUV = 0;
  39368. _this.OPACITYRGB = false;
  39369. _this.REFLECTION = false;
  39370. _this.EMISSIVE = false;
  39371. _this.EMISSIVEDIRECTUV = 0;
  39372. _this.SPECULAR = false;
  39373. _this.SPECULARDIRECTUV = 0;
  39374. _this.BUMP = false;
  39375. _this.BUMPDIRECTUV = 0;
  39376. _this.PARALLAX = false;
  39377. _this.PARALLAXOCCLUSION = false;
  39378. _this.SPECULAROVERALPHA = false;
  39379. _this.CLIPPLANE = false;
  39380. _this.ALPHATEST = false;
  39381. _this.DEPTHPREPASS = false;
  39382. _this.ALPHAFROMDIFFUSE = false;
  39383. _this.POINTSIZE = false;
  39384. _this.FOG = false;
  39385. _this.SPECULARTERM = false;
  39386. _this.DIFFUSEFRESNEL = false;
  39387. _this.OPACITYFRESNEL = false;
  39388. _this.REFLECTIONFRESNEL = false;
  39389. _this.REFRACTIONFRESNEL = false;
  39390. _this.EMISSIVEFRESNEL = false;
  39391. _this.FRESNEL = false;
  39392. _this.NORMAL = false;
  39393. _this.UV1 = false;
  39394. _this.UV2 = false;
  39395. _this.VERTEXCOLOR = false;
  39396. _this.VERTEXALPHA = false;
  39397. _this.NUM_BONE_INFLUENCERS = 0;
  39398. _this.BonesPerMesh = 0;
  39399. _this.INSTANCES = false;
  39400. _this.GLOSSINESS = false;
  39401. _this.ROUGHNESS = false;
  39402. _this.EMISSIVEASILLUMINATION = false;
  39403. _this.LINKEMISSIVEWITHDIFFUSE = false;
  39404. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  39405. _this.LIGHTMAP = false;
  39406. _this.LIGHTMAPDIRECTUV = 0;
  39407. _this.OBJECTSPACE_NORMALMAP = false;
  39408. _this.USELIGHTMAPASSHADOWMAP = false;
  39409. _this.REFLECTIONMAP_3D = false;
  39410. _this.REFLECTIONMAP_SPHERICAL = false;
  39411. _this.REFLECTIONMAP_PLANAR = false;
  39412. _this.REFLECTIONMAP_CUBIC = false;
  39413. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39414. _this.REFLECTIONMAP_PROJECTION = false;
  39415. _this.REFLECTIONMAP_SKYBOX = false;
  39416. _this.REFLECTIONMAP_EXPLICIT = false;
  39417. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39418. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39419. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39420. _this.INVERTCUBICMAP = false;
  39421. _this.LOGARITHMICDEPTH = false;
  39422. _this.REFRACTION = false;
  39423. _this.REFRACTIONMAP_3D = false;
  39424. _this.REFLECTIONOVERALPHA = false;
  39425. _this.TWOSIDEDLIGHTING = false;
  39426. _this.SHADOWFLOAT = false;
  39427. _this.MORPHTARGETS = false;
  39428. _this.MORPHTARGETS_NORMAL = false;
  39429. _this.MORPHTARGETS_TANGENT = false;
  39430. _this.NUM_MORPH_INFLUENCERS = 0;
  39431. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  39432. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  39433. _this.IMAGEPROCESSING = false;
  39434. _this.VIGNETTE = false;
  39435. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39436. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39437. _this.TONEMAPPING = false;
  39438. _this.CONTRAST = false;
  39439. _this.COLORCURVES = false;
  39440. _this.COLORGRADING = false;
  39441. _this.COLORGRADING3D = false;
  39442. _this.SAMPLER3DGREENDEPTH = false;
  39443. _this.SAMPLER3DBGRMAP = false;
  39444. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39445. _this.EXPOSURE = false;
  39446. _this.GRAIN = false;
  39447. _this.rebuild();
  39448. return _this;
  39449. }
  39450. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  39451. var modes = [
  39452. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  39453. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  39454. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  39455. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  39456. ];
  39457. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  39458. var mode = modes_1[_i];
  39459. this[mode] = (mode === modeToEnable);
  39460. }
  39461. };
  39462. return StandardMaterialDefines;
  39463. }(BABYLON.MaterialDefines));
  39464. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  39465. var StandardMaterial = /** @class */ (function (_super) {
  39466. __extends(StandardMaterial, _super);
  39467. function StandardMaterial(name, scene) {
  39468. var _this = _super.call(this, name, scene) || this;
  39469. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39470. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  39471. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  39472. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39473. _this.specularPower = 64;
  39474. _this._useAlphaFromDiffuseTexture = false;
  39475. _this._useEmissiveAsIllumination = false;
  39476. _this._linkEmissiveWithDiffuse = false;
  39477. _this._useSpecularOverAlpha = false;
  39478. _this._useReflectionOverAlpha = false;
  39479. _this._disableLighting = false;
  39480. _this._useObjectSpaceNormalMap = false;
  39481. _this._useParallax = false;
  39482. _this._useParallaxOcclusion = false;
  39483. _this.parallaxScaleBias = 0.05;
  39484. _this._roughness = 0;
  39485. _this.indexOfRefraction = 0.98;
  39486. _this.invertRefractionY = true;
  39487. _this._useLightmapAsShadowmap = false;
  39488. _this._useReflectionFresnelFromSpecular = false;
  39489. _this._useGlossinessFromSpecularMapAlpha = false;
  39490. _this._maxSimultaneousLights = 4;
  39491. /**
  39492. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39493. */
  39494. _this._invertNormalMapX = false;
  39495. /**
  39496. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39497. */
  39498. _this._invertNormalMapY = false;
  39499. /**
  39500. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39501. */
  39502. _this._twoSidedLighting = false;
  39503. _this._renderTargets = new BABYLON.SmartArray(16);
  39504. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  39505. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39506. // Setup the default processing configuration to the scene.
  39507. _this._attachImageProcessingConfiguration(null);
  39508. _this.getRenderTargetTextures = function () {
  39509. _this._renderTargets.reset();
  39510. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39511. _this._renderTargets.push(_this._reflectionTexture);
  39512. }
  39513. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39514. _this._renderTargets.push(_this._refractionTexture);
  39515. }
  39516. return _this._renderTargets;
  39517. };
  39518. return _this;
  39519. }
  39520. ;
  39521. ;
  39522. ;
  39523. ;
  39524. ;
  39525. ;
  39526. ;
  39527. ;
  39528. ;
  39529. ;
  39530. ;
  39531. ;
  39532. ;
  39533. ;
  39534. ;
  39535. ;
  39536. ;
  39537. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  39538. /**
  39539. * Gets the image processing configuration used either in this material.
  39540. */
  39541. get: function () {
  39542. return this._imageProcessingConfiguration;
  39543. },
  39544. /**
  39545. * Sets the Default image processing configuration used either in the this material.
  39546. *
  39547. * If sets to null, the scene one is in use.
  39548. */
  39549. set: function (value) {
  39550. this._attachImageProcessingConfiguration(value);
  39551. // Ensure the effect will be rebuilt.
  39552. this._markAllSubMeshesAsTexturesDirty();
  39553. },
  39554. enumerable: true,
  39555. configurable: true
  39556. });
  39557. /**
  39558. * Attaches a new image processing configuration to the Standard Material.
  39559. * @param configuration
  39560. */
  39561. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39562. var _this = this;
  39563. if (configuration === this._imageProcessingConfiguration) {
  39564. return;
  39565. }
  39566. // Detaches observer.
  39567. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39568. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39569. }
  39570. // Pick the scene configuration if needed.
  39571. if (!configuration) {
  39572. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39573. }
  39574. else {
  39575. this._imageProcessingConfiguration = configuration;
  39576. }
  39577. // Attaches observer.
  39578. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39579. _this._markAllSubMeshesAsImageProcessingDirty();
  39580. });
  39581. };
  39582. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  39583. /**
  39584. * Gets wether the color curves effect is enabled.
  39585. */
  39586. get: function () {
  39587. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39588. },
  39589. /**
  39590. * Sets wether the color curves effect is enabled.
  39591. */
  39592. set: function (value) {
  39593. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39594. },
  39595. enumerable: true,
  39596. configurable: true
  39597. });
  39598. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  39599. /**
  39600. * Gets wether the color grading effect is enabled.
  39601. */
  39602. get: function () {
  39603. return this.imageProcessingConfiguration.colorGradingEnabled;
  39604. },
  39605. /**
  39606. * Gets wether the color grading effect is enabled.
  39607. */
  39608. set: function (value) {
  39609. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39610. },
  39611. enumerable: true,
  39612. configurable: true
  39613. });
  39614. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  39615. /**
  39616. * Gets wether tonemapping is enabled or not.
  39617. */
  39618. get: function () {
  39619. return this._imageProcessingConfiguration.toneMappingEnabled;
  39620. },
  39621. /**
  39622. * Sets wether tonemapping is enabled or not
  39623. */
  39624. set: function (value) {
  39625. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39626. },
  39627. enumerable: true,
  39628. configurable: true
  39629. });
  39630. ;
  39631. ;
  39632. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39633. /**
  39634. * The camera exposure used on this material.
  39635. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39636. * This corresponds to a photographic exposure.
  39637. */
  39638. get: function () {
  39639. return this._imageProcessingConfiguration.exposure;
  39640. },
  39641. /**
  39642. * The camera exposure used on this material.
  39643. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39644. * This corresponds to a photographic exposure.
  39645. */
  39646. set: function (value) {
  39647. this._imageProcessingConfiguration.exposure = value;
  39648. },
  39649. enumerable: true,
  39650. configurable: true
  39651. });
  39652. ;
  39653. ;
  39654. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39655. /**
  39656. * Gets The camera contrast used on this material.
  39657. */
  39658. get: function () {
  39659. return this._imageProcessingConfiguration.contrast;
  39660. },
  39661. /**
  39662. * Sets The camera contrast used on this material.
  39663. */
  39664. set: function (value) {
  39665. this._imageProcessingConfiguration.contrast = value;
  39666. },
  39667. enumerable: true,
  39668. configurable: true
  39669. });
  39670. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39671. /**
  39672. * Gets the Color Grading 2D Lookup Texture.
  39673. */
  39674. get: function () {
  39675. return this._imageProcessingConfiguration.colorGradingTexture;
  39676. },
  39677. /**
  39678. * Sets the Color Grading 2D Lookup Texture.
  39679. */
  39680. set: function (value) {
  39681. this._imageProcessingConfiguration.colorGradingTexture = value;
  39682. },
  39683. enumerable: true,
  39684. configurable: true
  39685. });
  39686. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39687. /**
  39688. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39689. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39690. * 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;
  39691. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39692. */
  39693. get: function () {
  39694. return this._imageProcessingConfiguration.colorCurves;
  39695. },
  39696. /**
  39697. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39698. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39699. * 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;
  39700. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39701. */
  39702. set: function (value) {
  39703. this._imageProcessingConfiguration.colorCurves = value;
  39704. },
  39705. enumerable: true,
  39706. configurable: true
  39707. });
  39708. StandardMaterial.prototype.getClassName = function () {
  39709. return "StandardMaterial";
  39710. };
  39711. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39712. get: function () {
  39713. return this._useLogarithmicDepth;
  39714. },
  39715. set: function (value) {
  39716. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39717. this._markAllSubMeshesAsMiscDirty();
  39718. },
  39719. enumerable: true,
  39720. configurable: true
  39721. });
  39722. StandardMaterial.prototype.needAlphaBlending = function () {
  39723. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39724. };
  39725. StandardMaterial.prototype.needAlphaTesting = function () {
  39726. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39727. };
  39728. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39729. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39730. };
  39731. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39732. return this._diffuseTexture;
  39733. };
  39734. /**
  39735. * Child classes can use it to update shaders
  39736. */
  39737. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39738. if (useInstances === void 0) { useInstances = false; }
  39739. if (subMesh.effect && this.isFrozen) {
  39740. if (this._wasPreviouslyReady && subMesh.effect) {
  39741. return true;
  39742. }
  39743. }
  39744. if (!subMesh._materialDefines) {
  39745. subMesh._materialDefines = new StandardMaterialDefines();
  39746. }
  39747. var scene = this.getScene();
  39748. var defines = subMesh._materialDefines;
  39749. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39750. if (defines._renderId === scene.getRenderId()) {
  39751. return true;
  39752. }
  39753. }
  39754. var engine = scene.getEngine();
  39755. // Lights
  39756. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39757. // Textures
  39758. if (defines._areTexturesDirty) {
  39759. defines._needUVs = false;
  39760. defines.MAINUV1 = false;
  39761. defines.MAINUV2 = false;
  39762. if (scene.texturesEnabled) {
  39763. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39764. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39765. return false;
  39766. }
  39767. else {
  39768. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39769. }
  39770. }
  39771. else {
  39772. defines.DIFFUSE = false;
  39773. }
  39774. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39775. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39776. return false;
  39777. }
  39778. else {
  39779. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39780. }
  39781. }
  39782. else {
  39783. defines.AMBIENT = false;
  39784. }
  39785. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39786. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39787. return false;
  39788. }
  39789. else {
  39790. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39791. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39792. }
  39793. }
  39794. else {
  39795. defines.OPACITY = false;
  39796. }
  39797. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39798. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39799. return false;
  39800. }
  39801. else {
  39802. defines._needNormals = true;
  39803. defines.REFLECTION = true;
  39804. defines.ROUGHNESS = (this._roughness > 0);
  39805. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39806. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39807. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39808. switch (this._reflectionTexture.coordinatesMode) {
  39809. case BABYLON.Texture.CUBIC_MODE:
  39810. case BABYLON.Texture.INVCUBIC_MODE:
  39811. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39812. break;
  39813. case BABYLON.Texture.EXPLICIT_MODE:
  39814. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39815. break;
  39816. case BABYLON.Texture.PLANAR_MODE:
  39817. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39818. break;
  39819. case BABYLON.Texture.PROJECTION_MODE:
  39820. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39821. break;
  39822. case BABYLON.Texture.SKYBOX_MODE:
  39823. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39824. break;
  39825. case BABYLON.Texture.SPHERICAL_MODE:
  39826. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39827. break;
  39828. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39829. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39830. break;
  39831. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39832. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39833. break;
  39834. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39835. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39836. break;
  39837. }
  39838. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39839. }
  39840. }
  39841. else {
  39842. defines.REFLECTION = false;
  39843. }
  39844. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39845. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39846. return false;
  39847. }
  39848. else {
  39849. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39850. }
  39851. }
  39852. else {
  39853. defines.EMISSIVE = false;
  39854. }
  39855. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39856. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39857. return false;
  39858. }
  39859. else {
  39860. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39861. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39862. }
  39863. }
  39864. else {
  39865. defines.LIGHTMAP = false;
  39866. }
  39867. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39868. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39869. return false;
  39870. }
  39871. else {
  39872. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39873. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39874. }
  39875. }
  39876. else {
  39877. defines.SPECULAR = false;
  39878. }
  39879. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39880. // Bump texure can not be not blocking.
  39881. if (!this._bumpTexture.isReady()) {
  39882. return false;
  39883. }
  39884. else {
  39885. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39886. defines.PARALLAX = this._useParallax;
  39887. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39888. }
  39889. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39890. }
  39891. else {
  39892. defines.BUMP = false;
  39893. }
  39894. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39895. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39896. return false;
  39897. }
  39898. else {
  39899. defines._needUVs = true;
  39900. defines.REFRACTION = true;
  39901. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39902. }
  39903. }
  39904. else {
  39905. defines.REFRACTION = false;
  39906. }
  39907. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39908. }
  39909. else {
  39910. defines.DIFFUSE = false;
  39911. defines.AMBIENT = false;
  39912. defines.OPACITY = false;
  39913. defines.REFLECTION = false;
  39914. defines.EMISSIVE = false;
  39915. defines.LIGHTMAP = false;
  39916. defines.BUMP = false;
  39917. defines.REFRACTION = false;
  39918. }
  39919. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39920. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39921. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39922. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39923. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39924. }
  39925. if (defines._areImageProcessingDirty) {
  39926. if (!this._imageProcessingConfiguration.isReady()) {
  39927. return false;
  39928. }
  39929. this._imageProcessingConfiguration.prepareDefines(defines);
  39930. }
  39931. if (defines._areFresnelDirty) {
  39932. if (StandardMaterial.FresnelEnabled) {
  39933. // Fresnel
  39934. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39935. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39936. this._reflectionFresnelParameters) {
  39937. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  39938. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  39939. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  39940. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  39941. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  39942. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  39943. defines._needNormals = true;
  39944. defines.FRESNEL = true;
  39945. }
  39946. }
  39947. else {
  39948. defines.FRESNEL = false;
  39949. }
  39950. }
  39951. // Misc.
  39952. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  39953. // Attribs
  39954. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  39955. // Values that need to be evaluated on every frame
  39956. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  39957. // Get correct effect
  39958. if (defines.isDirty) {
  39959. defines.markAsProcessed();
  39960. scene.resetCachedMaterial();
  39961. // Fallbacks
  39962. var fallbacks = new BABYLON.EffectFallbacks();
  39963. if (defines.REFLECTION) {
  39964. fallbacks.addFallback(0, "REFLECTION");
  39965. }
  39966. if (defines.SPECULAR) {
  39967. fallbacks.addFallback(0, "SPECULAR");
  39968. }
  39969. if (defines.BUMP) {
  39970. fallbacks.addFallback(0, "BUMP");
  39971. }
  39972. if (defines.PARALLAX) {
  39973. fallbacks.addFallback(1, "PARALLAX");
  39974. }
  39975. if (defines.PARALLAXOCCLUSION) {
  39976. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  39977. }
  39978. if (defines.SPECULAROVERALPHA) {
  39979. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  39980. }
  39981. if (defines.FOG) {
  39982. fallbacks.addFallback(1, "FOG");
  39983. }
  39984. if (defines.POINTSIZE) {
  39985. fallbacks.addFallback(0, "POINTSIZE");
  39986. }
  39987. if (defines.LOGARITHMICDEPTH) {
  39988. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  39989. }
  39990. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  39991. if (defines.SPECULARTERM) {
  39992. fallbacks.addFallback(0, "SPECULARTERM");
  39993. }
  39994. if (defines.DIFFUSEFRESNEL) {
  39995. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  39996. }
  39997. if (defines.OPACITYFRESNEL) {
  39998. fallbacks.addFallback(2, "OPACITYFRESNEL");
  39999. }
  40000. if (defines.REFLECTIONFRESNEL) {
  40001. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  40002. }
  40003. if (defines.EMISSIVEFRESNEL) {
  40004. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  40005. }
  40006. if (defines.FRESNEL) {
  40007. fallbacks.addFallback(4, "FRESNEL");
  40008. }
  40009. //Attributes
  40010. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40011. if (defines.NORMAL) {
  40012. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40013. }
  40014. if (defines.UV1) {
  40015. attribs.push(BABYLON.VertexBuffer.UVKind);
  40016. }
  40017. if (defines.UV2) {
  40018. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40019. }
  40020. if (defines.VERTEXCOLOR) {
  40021. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40022. }
  40023. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40024. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40025. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40026. var shaderName = "default";
  40027. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  40028. "vFogInfos", "vFogColor", "pointSize",
  40029. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40030. "mBones",
  40031. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  40032. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  40033. "vReflectionPosition", "vReflectionSize",
  40034. "logarithmicDepthConstant", "vTangentSpaceParams"
  40035. ];
  40036. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  40037. var uniformBuffers = ["Material", "Scene"];
  40038. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40039. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40040. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40041. uniformsNames: uniforms,
  40042. uniformBuffersNames: uniformBuffers,
  40043. samplers: samplers,
  40044. defines: defines,
  40045. maxSimultaneousLights: this._maxSimultaneousLights
  40046. });
  40047. if (this.customShaderNameResolve) {
  40048. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  40049. }
  40050. var join = defines.toString();
  40051. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  40052. attributes: attribs,
  40053. uniformsNames: uniforms,
  40054. uniformBuffersNames: uniformBuffers,
  40055. samplers: samplers,
  40056. defines: join,
  40057. fallbacks: fallbacks,
  40058. onCompiled: this.onCompiled,
  40059. onError: this.onError,
  40060. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40061. }, engine), defines);
  40062. this.buildUniformLayout();
  40063. }
  40064. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40065. return false;
  40066. }
  40067. defines._renderId = scene.getRenderId();
  40068. this._wasPreviouslyReady = true;
  40069. return true;
  40070. };
  40071. StandardMaterial.prototype.buildUniformLayout = function () {
  40072. // Order is important !
  40073. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  40074. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  40075. this._uniformBuffer.addUniform("opacityParts", 4);
  40076. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  40077. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  40078. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  40079. this._uniformBuffer.addUniform("refractionRightColor", 4);
  40080. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  40081. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  40082. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  40083. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  40084. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  40085. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  40086. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  40087. this._uniformBuffer.addUniform("vReflectionSize", 3);
  40088. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  40089. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  40090. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  40091. this._uniformBuffer.addUniform("vBumpInfos", 3);
  40092. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  40093. this._uniformBuffer.addUniform("ambientMatrix", 16);
  40094. this._uniformBuffer.addUniform("opacityMatrix", 16);
  40095. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  40096. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  40097. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  40098. this._uniformBuffer.addUniform("specularMatrix", 16);
  40099. this._uniformBuffer.addUniform("bumpMatrix", 16);
  40100. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  40101. this._uniformBuffer.addUniform("refractionMatrix", 16);
  40102. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  40103. this._uniformBuffer.addUniform("vSpecularColor", 4);
  40104. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  40105. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  40106. this._uniformBuffer.addUniform("pointSize", 1);
  40107. this._uniformBuffer.create();
  40108. };
  40109. StandardMaterial.prototype.unbind = function () {
  40110. if (this._activeEffect) {
  40111. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  40112. this._activeEffect.setTexture("reflection2DSampler", null);
  40113. }
  40114. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40115. this._activeEffect.setTexture("refraction2DSampler", null);
  40116. }
  40117. }
  40118. _super.prototype.unbind.call(this);
  40119. };
  40120. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40121. var scene = this.getScene();
  40122. var defines = subMesh._materialDefines;
  40123. if (!defines) {
  40124. return;
  40125. }
  40126. var effect = subMesh.effect;
  40127. if (!effect) {
  40128. return;
  40129. }
  40130. this._activeEffect = effect;
  40131. // Matrices
  40132. this.bindOnlyWorldMatrix(world);
  40133. // Normal Matrix
  40134. if (defines.OBJECTSPACE_NORMALMAP) {
  40135. world.toNormalMatrix(this._normalMatrix);
  40136. this.bindOnlyNormalMatrix(this._normalMatrix);
  40137. }
  40138. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  40139. // Bones
  40140. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  40141. if (mustRebind) {
  40142. this._uniformBuffer.bindToEffect(effect, "Material");
  40143. this.bindViewProjection(effect);
  40144. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40145. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  40146. // Fresnel
  40147. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  40148. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  40149. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  40150. }
  40151. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  40152. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  40153. }
  40154. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  40155. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  40156. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  40157. }
  40158. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  40159. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  40160. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  40161. }
  40162. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  40163. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  40164. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  40165. }
  40166. }
  40167. // Textures
  40168. if (scene.texturesEnabled) {
  40169. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40170. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  40171. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  40172. }
  40173. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40174. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  40175. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  40176. }
  40177. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40178. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  40179. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  40180. }
  40181. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40182. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  40183. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  40184. if (this._reflectionTexture.boundingBoxSize) {
  40185. var cubeTexture = this._reflectionTexture;
  40186. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  40187. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  40188. }
  40189. }
  40190. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40191. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  40192. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  40193. }
  40194. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40195. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  40196. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  40197. }
  40198. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40199. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  40200. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  40201. }
  40202. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40203. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  40204. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  40205. if (scene._mirroredCameraPosition) {
  40206. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  40207. }
  40208. else {
  40209. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  40210. }
  40211. }
  40212. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40213. var depth = 1.0;
  40214. if (!this._refractionTexture.isCube) {
  40215. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  40216. if (this._refractionTexture.depth) {
  40217. depth = this._refractionTexture.depth;
  40218. }
  40219. }
  40220. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  40221. }
  40222. }
  40223. // Point size
  40224. if (this.pointsCloud) {
  40225. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  40226. }
  40227. if (defines.SPECULARTERM) {
  40228. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  40229. }
  40230. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  40231. // Diffuse
  40232. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  40233. }
  40234. // Textures
  40235. if (scene.texturesEnabled) {
  40236. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40237. effect.setTexture("diffuseSampler", this._diffuseTexture);
  40238. }
  40239. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40240. effect.setTexture("ambientSampler", this._ambientTexture);
  40241. }
  40242. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40243. effect.setTexture("opacitySampler", this._opacityTexture);
  40244. }
  40245. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40246. if (this._reflectionTexture.isCube) {
  40247. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  40248. }
  40249. else {
  40250. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  40251. }
  40252. }
  40253. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40254. effect.setTexture("emissiveSampler", this._emissiveTexture);
  40255. }
  40256. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40257. effect.setTexture("lightmapSampler", this._lightmapTexture);
  40258. }
  40259. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40260. effect.setTexture("specularSampler", this._specularTexture);
  40261. }
  40262. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40263. effect.setTexture("bumpSampler", this._bumpTexture);
  40264. }
  40265. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40266. var depth = 1.0;
  40267. if (this._refractionTexture.isCube) {
  40268. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  40269. }
  40270. else {
  40271. effect.setTexture("refraction2DSampler", this._refractionTexture);
  40272. }
  40273. }
  40274. }
  40275. // Clip plane
  40276. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  40277. // Colors
  40278. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  40279. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  40280. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  40281. }
  40282. if (mustRebind || !this.isFrozen) {
  40283. // Lights
  40284. if (scene.lightsEnabled && !this._disableLighting) {
  40285. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  40286. }
  40287. // View
  40288. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  40289. this.bindView(effect);
  40290. }
  40291. // Fog
  40292. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  40293. // Morph targets
  40294. if (defines.NUM_MORPH_INFLUENCERS) {
  40295. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  40296. }
  40297. // Log. depth
  40298. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  40299. // image processing
  40300. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  40301. this._imageProcessingConfiguration.bind(this._activeEffect);
  40302. }
  40303. }
  40304. this._uniformBuffer.update();
  40305. this._afterBind(mesh, this._activeEffect);
  40306. };
  40307. StandardMaterial.prototype.getAnimatables = function () {
  40308. var results = [];
  40309. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  40310. results.push(this._diffuseTexture);
  40311. }
  40312. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  40313. results.push(this._ambientTexture);
  40314. }
  40315. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  40316. results.push(this._opacityTexture);
  40317. }
  40318. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  40319. results.push(this._reflectionTexture);
  40320. }
  40321. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  40322. results.push(this._emissiveTexture);
  40323. }
  40324. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  40325. results.push(this._specularTexture);
  40326. }
  40327. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  40328. results.push(this._bumpTexture);
  40329. }
  40330. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  40331. results.push(this._lightmapTexture);
  40332. }
  40333. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  40334. results.push(this._refractionTexture);
  40335. }
  40336. return results;
  40337. };
  40338. StandardMaterial.prototype.getActiveTextures = function () {
  40339. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40340. if (this._diffuseTexture) {
  40341. activeTextures.push(this._diffuseTexture);
  40342. }
  40343. if (this._ambientTexture) {
  40344. activeTextures.push(this._ambientTexture);
  40345. }
  40346. if (this._opacityTexture) {
  40347. activeTextures.push(this._opacityTexture);
  40348. }
  40349. if (this._reflectionTexture) {
  40350. activeTextures.push(this._reflectionTexture);
  40351. }
  40352. if (this._emissiveTexture) {
  40353. activeTextures.push(this._emissiveTexture);
  40354. }
  40355. if (this._specularTexture) {
  40356. activeTextures.push(this._specularTexture);
  40357. }
  40358. if (this._bumpTexture) {
  40359. activeTextures.push(this._bumpTexture);
  40360. }
  40361. if (this._lightmapTexture) {
  40362. activeTextures.push(this._lightmapTexture);
  40363. }
  40364. if (this._refractionTexture) {
  40365. activeTextures.push(this._refractionTexture);
  40366. }
  40367. return activeTextures;
  40368. };
  40369. StandardMaterial.prototype.hasTexture = function (texture) {
  40370. if (_super.prototype.hasTexture.call(this, texture)) {
  40371. return true;
  40372. }
  40373. if (this._diffuseTexture === texture) {
  40374. return true;
  40375. }
  40376. if (this._ambientTexture === texture) {
  40377. return true;
  40378. }
  40379. if (this._opacityTexture === texture) {
  40380. return true;
  40381. }
  40382. if (this._reflectionTexture === texture) {
  40383. return true;
  40384. }
  40385. if (this._emissiveTexture === texture) {
  40386. return true;
  40387. }
  40388. if (this._specularTexture === texture) {
  40389. return true;
  40390. }
  40391. if (this._bumpTexture === texture) {
  40392. return true;
  40393. }
  40394. if (this._lightmapTexture === texture) {
  40395. return true;
  40396. }
  40397. if (this._refractionTexture === texture) {
  40398. return true;
  40399. }
  40400. return false;
  40401. };
  40402. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40403. if (forceDisposeTextures) {
  40404. if (this._diffuseTexture) {
  40405. this._diffuseTexture.dispose();
  40406. }
  40407. if (this._ambientTexture) {
  40408. this._ambientTexture.dispose();
  40409. }
  40410. if (this._opacityTexture) {
  40411. this._opacityTexture.dispose();
  40412. }
  40413. if (this._reflectionTexture) {
  40414. this._reflectionTexture.dispose();
  40415. }
  40416. if (this._emissiveTexture) {
  40417. this._emissiveTexture.dispose();
  40418. }
  40419. if (this._specularTexture) {
  40420. this._specularTexture.dispose();
  40421. }
  40422. if (this._bumpTexture) {
  40423. this._bumpTexture.dispose();
  40424. }
  40425. if (this._lightmapTexture) {
  40426. this._lightmapTexture.dispose();
  40427. }
  40428. if (this._refractionTexture) {
  40429. this._refractionTexture.dispose();
  40430. }
  40431. }
  40432. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40433. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40434. }
  40435. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40436. };
  40437. StandardMaterial.prototype.clone = function (name) {
  40438. var _this = this;
  40439. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  40440. result.name = name;
  40441. result.id = name;
  40442. return result;
  40443. };
  40444. StandardMaterial.prototype.serialize = function () {
  40445. return BABYLON.SerializationHelper.Serialize(this);
  40446. };
  40447. // Statics
  40448. StandardMaterial.Parse = function (source, scene, rootUrl) {
  40449. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  40450. };
  40451. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  40452. get: function () {
  40453. return StandardMaterial._DiffuseTextureEnabled;
  40454. },
  40455. set: function (value) {
  40456. if (StandardMaterial._DiffuseTextureEnabled === value) {
  40457. return;
  40458. }
  40459. StandardMaterial._DiffuseTextureEnabled = value;
  40460. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40461. },
  40462. enumerable: true,
  40463. configurable: true
  40464. });
  40465. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  40466. get: function () {
  40467. return StandardMaterial._AmbientTextureEnabled;
  40468. },
  40469. set: function (value) {
  40470. if (StandardMaterial._AmbientTextureEnabled === value) {
  40471. return;
  40472. }
  40473. StandardMaterial._AmbientTextureEnabled = value;
  40474. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40475. },
  40476. enumerable: true,
  40477. configurable: true
  40478. });
  40479. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  40480. get: function () {
  40481. return StandardMaterial._OpacityTextureEnabled;
  40482. },
  40483. set: function (value) {
  40484. if (StandardMaterial._OpacityTextureEnabled === value) {
  40485. return;
  40486. }
  40487. StandardMaterial._OpacityTextureEnabled = value;
  40488. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40489. },
  40490. enumerable: true,
  40491. configurable: true
  40492. });
  40493. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  40494. get: function () {
  40495. return StandardMaterial._ReflectionTextureEnabled;
  40496. },
  40497. set: function (value) {
  40498. if (StandardMaterial._ReflectionTextureEnabled === value) {
  40499. return;
  40500. }
  40501. StandardMaterial._ReflectionTextureEnabled = value;
  40502. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40503. },
  40504. enumerable: true,
  40505. configurable: true
  40506. });
  40507. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  40508. get: function () {
  40509. return StandardMaterial._EmissiveTextureEnabled;
  40510. },
  40511. set: function (value) {
  40512. if (StandardMaterial._EmissiveTextureEnabled === value) {
  40513. return;
  40514. }
  40515. StandardMaterial._EmissiveTextureEnabled = value;
  40516. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40517. },
  40518. enumerable: true,
  40519. configurable: true
  40520. });
  40521. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  40522. get: function () {
  40523. return StandardMaterial._SpecularTextureEnabled;
  40524. },
  40525. set: function (value) {
  40526. if (StandardMaterial._SpecularTextureEnabled === value) {
  40527. return;
  40528. }
  40529. StandardMaterial._SpecularTextureEnabled = value;
  40530. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40531. },
  40532. enumerable: true,
  40533. configurable: true
  40534. });
  40535. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  40536. get: function () {
  40537. return StandardMaterial._BumpTextureEnabled;
  40538. },
  40539. set: function (value) {
  40540. if (StandardMaterial._BumpTextureEnabled === value) {
  40541. return;
  40542. }
  40543. StandardMaterial._BumpTextureEnabled = value;
  40544. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40545. },
  40546. enumerable: true,
  40547. configurable: true
  40548. });
  40549. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  40550. get: function () {
  40551. return StandardMaterial._LightmapTextureEnabled;
  40552. },
  40553. set: function (value) {
  40554. if (StandardMaterial._LightmapTextureEnabled === value) {
  40555. return;
  40556. }
  40557. StandardMaterial._LightmapTextureEnabled = value;
  40558. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40559. },
  40560. enumerable: true,
  40561. configurable: true
  40562. });
  40563. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  40564. get: function () {
  40565. return StandardMaterial._RefractionTextureEnabled;
  40566. },
  40567. set: function (value) {
  40568. if (StandardMaterial._RefractionTextureEnabled === value) {
  40569. return;
  40570. }
  40571. StandardMaterial._RefractionTextureEnabled = value;
  40572. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40573. },
  40574. enumerable: true,
  40575. configurable: true
  40576. });
  40577. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  40578. get: function () {
  40579. return StandardMaterial._ColorGradingTextureEnabled;
  40580. },
  40581. set: function (value) {
  40582. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  40583. return;
  40584. }
  40585. StandardMaterial._ColorGradingTextureEnabled = value;
  40586. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40587. },
  40588. enumerable: true,
  40589. configurable: true
  40590. });
  40591. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  40592. get: function () {
  40593. return StandardMaterial._FresnelEnabled;
  40594. },
  40595. set: function (value) {
  40596. if (StandardMaterial._FresnelEnabled === value) {
  40597. return;
  40598. }
  40599. StandardMaterial._FresnelEnabled = value;
  40600. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  40601. },
  40602. enumerable: true,
  40603. configurable: true
  40604. });
  40605. // Flags used to enable or disable a type of texture for all Standard Materials
  40606. StandardMaterial._DiffuseTextureEnabled = true;
  40607. StandardMaterial._AmbientTextureEnabled = true;
  40608. StandardMaterial._OpacityTextureEnabled = true;
  40609. StandardMaterial._ReflectionTextureEnabled = true;
  40610. StandardMaterial._EmissiveTextureEnabled = true;
  40611. StandardMaterial._SpecularTextureEnabled = true;
  40612. StandardMaterial._BumpTextureEnabled = true;
  40613. StandardMaterial._LightmapTextureEnabled = true;
  40614. StandardMaterial._RefractionTextureEnabled = true;
  40615. StandardMaterial._ColorGradingTextureEnabled = true;
  40616. StandardMaterial._FresnelEnabled = true;
  40617. __decorate([
  40618. BABYLON.serializeAsTexture("diffuseTexture")
  40619. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40620. __decorate([
  40621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40622. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40623. __decorate([
  40624. BABYLON.serializeAsTexture("ambientTexture")
  40625. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40626. __decorate([
  40627. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40628. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40629. __decorate([
  40630. BABYLON.serializeAsTexture("opacityTexture")
  40631. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40632. __decorate([
  40633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40634. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40635. __decorate([
  40636. BABYLON.serializeAsTexture("reflectionTexture")
  40637. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40638. __decorate([
  40639. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40640. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40641. __decorate([
  40642. BABYLON.serializeAsTexture("emissiveTexture")
  40643. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40644. __decorate([
  40645. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40646. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40647. __decorate([
  40648. BABYLON.serializeAsTexture("specularTexture")
  40649. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40650. __decorate([
  40651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40652. ], StandardMaterial.prototype, "specularTexture", void 0);
  40653. __decorate([
  40654. BABYLON.serializeAsTexture("bumpTexture")
  40655. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40656. __decorate([
  40657. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40658. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40659. __decorate([
  40660. BABYLON.serializeAsTexture("lightmapTexture")
  40661. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40662. __decorate([
  40663. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40664. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40665. __decorate([
  40666. BABYLON.serializeAsTexture("refractionTexture")
  40667. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40668. __decorate([
  40669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40670. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40671. __decorate([
  40672. BABYLON.serializeAsColor3("ambient")
  40673. ], StandardMaterial.prototype, "ambientColor", void 0);
  40674. __decorate([
  40675. BABYLON.serializeAsColor3("diffuse")
  40676. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40677. __decorate([
  40678. BABYLON.serializeAsColor3("specular")
  40679. ], StandardMaterial.prototype, "specularColor", void 0);
  40680. __decorate([
  40681. BABYLON.serializeAsColor3("emissive")
  40682. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40683. __decorate([
  40684. BABYLON.serialize()
  40685. ], StandardMaterial.prototype, "specularPower", void 0);
  40686. __decorate([
  40687. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40688. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40689. __decorate([
  40690. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40691. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40692. __decorate([
  40693. BABYLON.serialize("useEmissiveAsIllumination")
  40694. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40695. __decorate([
  40696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40697. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40698. __decorate([
  40699. BABYLON.serialize("linkEmissiveWithDiffuse")
  40700. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40701. __decorate([
  40702. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40703. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40704. __decorate([
  40705. BABYLON.serialize("useSpecularOverAlpha")
  40706. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40707. __decorate([
  40708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40709. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40710. __decorate([
  40711. BABYLON.serialize("useReflectionOverAlpha")
  40712. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40713. __decorate([
  40714. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40715. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40716. __decorate([
  40717. BABYLON.serialize("disableLighting")
  40718. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40719. __decorate([
  40720. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40721. ], StandardMaterial.prototype, "disableLighting", void 0);
  40722. __decorate([
  40723. BABYLON.serialize("useObjectSpaceNormalMap")
  40724. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40725. __decorate([
  40726. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40727. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40728. __decorate([
  40729. BABYLON.serialize("useParallax")
  40730. ], StandardMaterial.prototype, "_useParallax", void 0);
  40731. __decorate([
  40732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40733. ], StandardMaterial.prototype, "useParallax", void 0);
  40734. __decorate([
  40735. BABYLON.serialize("useParallaxOcclusion")
  40736. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40737. __decorate([
  40738. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40739. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40740. __decorate([
  40741. BABYLON.serialize()
  40742. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40743. __decorate([
  40744. BABYLON.serialize("roughness")
  40745. ], StandardMaterial.prototype, "_roughness", void 0);
  40746. __decorate([
  40747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40748. ], StandardMaterial.prototype, "roughness", void 0);
  40749. __decorate([
  40750. BABYLON.serialize()
  40751. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40752. __decorate([
  40753. BABYLON.serialize()
  40754. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40755. __decorate([
  40756. BABYLON.serialize("useLightmapAsShadowmap")
  40757. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40758. __decorate([
  40759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40760. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40761. __decorate([
  40762. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40763. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40764. __decorate([
  40765. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40766. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40767. __decorate([
  40768. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40769. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40770. __decorate([
  40771. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40772. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40773. __decorate([
  40774. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40775. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40776. __decorate([
  40777. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40778. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40779. __decorate([
  40780. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40781. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40782. __decorate([
  40783. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40784. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40785. __decorate([
  40786. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40787. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40788. __decorate([
  40789. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40790. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40791. __decorate([
  40792. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40793. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40794. __decorate([
  40795. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40796. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40797. __decorate([
  40798. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40799. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40800. __decorate([
  40801. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40802. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40803. __decorate([
  40804. BABYLON.serialize("maxSimultaneousLights")
  40805. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40806. __decorate([
  40807. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40808. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40809. __decorate([
  40810. BABYLON.serialize("invertNormalMapX")
  40811. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40812. __decorate([
  40813. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40814. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40815. __decorate([
  40816. BABYLON.serialize("invertNormalMapY")
  40817. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40818. __decorate([
  40819. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40820. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40821. __decorate([
  40822. BABYLON.serialize("twoSidedLighting")
  40823. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40824. __decorate([
  40825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40826. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40827. __decorate([
  40828. BABYLON.serialize()
  40829. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40830. return StandardMaterial;
  40831. }(BABYLON.PushMaterial));
  40832. BABYLON.StandardMaterial = StandardMaterial;
  40833. })(BABYLON || (BABYLON = {}));
  40834. //# sourceMappingURL=babylon.standardMaterial.js.map
  40835. "use strict";
  40836. var BABYLON;
  40837. (function (BABYLON) {
  40838. /**
  40839. * Manages the defines for the PBR Material.
  40840. */
  40841. var PBRMaterialDefines = /** @class */ (function (_super) {
  40842. __extends(PBRMaterialDefines, _super);
  40843. /**
  40844. * Initializes the PBR Material defines.
  40845. */
  40846. function PBRMaterialDefines() {
  40847. var _this = _super.call(this) || this;
  40848. _this.PBR = true;
  40849. _this.MAINUV1 = false;
  40850. _this.MAINUV2 = false;
  40851. _this.UV1 = false;
  40852. _this.UV2 = false;
  40853. _this.ALBEDO = false;
  40854. _this.ALBEDODIRECTUV = 0;
  40855. _this.VERTEXCOLOR = false;
  40856. _this.AMBIENT = false;
  40857. _this.AMBIENTDIRECTUV = 0;
  40858. _this.AMBIENTINGRAYSCALE = false;
  40859. _this.OPACITY = false;
  40860. _this.VERTEXALPHA = false;
  40861. _this.OPACITYDIRECTUV = 0;
  40862. _this.OPACITYRGB = false;
  40863. _this.ALPHATEST = false;
  40864. _this.DEPTHPREPASS = false;
  40865. _this.ALPHABLEND = false;
  40866. _this.ALPHAFROMALBEDO = false;
  40867. _this.ALPHATESTVALUE = "0.5";
  40868. _this.SPECULAROVERALPHA = false;
  40869. _this.RADIANCEOVERALPHA = false;
  40870. _this.ALPHAFRESNEL = false;
  40871. _this.LINEARALPHAFRESNEL = false;
  40872. _this.PREMULTIPLYALPHA = false;
  40873. _this.EMISSIVE = false;
  40874. _this.EMISSIVEDIRECTUV = 0;
  40875. _this.REFLECTIVITY = false;
  40876. _this.REFLECTIVITYDIRECTUV = 0;
  40877. _this.SPECULARTERM = false;
  40878. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40879. _this.MICROSURFACEAUTOMATIC = false;
  40880. _this.LODBASEDMICROSFURACE = false;
  40881. _this.MICROSURFACEMAP = false;
  40882. _this.MICROSURFACEMAPDIRECTUV = 0;
  40883. _this.METALLICWORKFLOW = false;
  40884. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40885. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40886. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40887. _this.AOSTOREINMETALMAPRED = false;
  40888. _this.ENVIRONMENTBRDF = false;
  40889. _this.NORMAL = false;
  40890. _this.TANGENT = false;
  40891. _this.BUMP = false;
  40892. _this.BUMPDIRECTUV = 0;
  40893. _this.OBJECTSPACE_NORMALMAP = false;
  40894. _this.PARALLAX = false;
  40895. _this.PARALLAXOCCLUSION = false;
  40896. _this.NORMALXYSCALE = true;
  40897. _this.LIGHTMAP = false;
  40898. _this.LIGHTMAPDIRECTUV = 0;
  40899. _this.USELIGHTMAPASSHADOWMAP = false;
  40900. _this.GAMMALIGHTMAP = false;
  40901. _this.REFLECTION = false;
  40902. _this.REFLECTIONMAP_3D = false;
  40903. _this.REFLECTIONMAP_SPHERICAL = false;
  40904. _this.REFLECTIONMAP_PLANAR = false;
  40905. _this.REFLECTIONMAP_CUBIC = false;
  40906. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40907. _this.REFLECTIONMAP_PROJECTION = false;
  40908. _this.REFLECTIONMAP_SKYBOX = false;
  40909. _this.REFLECTIONMAP_EXPLICIT = false;
  40910. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40911. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40912. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40913. _this.INVERTCUBICMAP = false;
  40914. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40915. _this.USESPHERICALINVERTEX = false;
  40916. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40917. _this.LODINREFLECTIONALPHA = false;
  40918. _this.GAMMAREFLECTION = false;
  40919. _this.RADIANCEOCCLUSION = false;
  40920. _this.HORIZONOCCLUSION = false;
  40921. _this.REFRACTION = false;
  40922. _this.REFRACTIONMAP_3D = false;
  40923. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40924. _this.LODINREFRACTIONALPHA = false;
  40925. _this.GAMMAREFRACTION = false;
  40926. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40927. _this.INSTANCES = false;
  40928. _this.NUM_BONE_INFLUENCERS = 0;
  40929. _this.BonesPerMesh = 0;
  40930. _this.NONUNIFORMSCALING = false;
  40931. _this.MORPHTARGETS = false;
  40932. _this.MORPHTARGETS_NORMAL = false;
  40933. _this.MORPHTARGETS_TANGENT = false;
  40934. _this.NUM_MORPH_INFLUENCERS = 0;
  40935. _this.IMAGEPROCESSING = false;
  40936. _this.VIGNETTE = false;
  40937. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40938. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40939. _this.TONEMAPPING = false;
  40940. _this.CONTRAST = false;
  40941. _this.COLORCURVES = false;
  40942. _this.COLORGRADING = false;
  40943. _this.COLORGRADING3D = false;
  40944. _this.SAMPLER3DGREENDEPTH = false;
  40945. _this.SAMPLER3DBGRMAP = false;
  40946. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40947. _this.EXPOSURE = false;
  40948. _this.GRAIN = false;
  40949. _this.USEPHYSICALLIGHTFALLOFF = false;
  40950. _this.TWOSIDEDLIGHTING = false;
  40951. _this.SHADOWFLOAT = false;
  40952. _this.CLIPPLANE = false;
  40953. _this.POINTSIZE = false;
  40954. _this.FOG = false;
  40955. _this.LOGARITHMICDEPTH = false;
  40956. _this.FORCENORMALFORWARD = false;
  40957. _this.UNLIT = false;
  40958. _this.rebuild();
  40959. return _this;
  40960. }
  40961. /**
  40962. * Resets the PBR Material defines.
  40963. */
  40964. PBRMaterialDefines.prototype.reset = function () {
  40965. _super.prototype.reset.call(this);
  40966. this.ALPHATESTVALUE = "0.5";
  40967. this.PBR = true;
  40968. };
  40969. return PBRMaterialDefines;
  40970. }(BABYLON.MaterialDefines));
  40971. /**
  40972. * The Physically based material base class of BJS.
  40973. *
  40974. * This offers the main features of a standard PBR material.
  40975. * For more information, please refer to the documentation :
  40976. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  40977. */
  40978. var PBRBaseMaterial = /** @class */ (function (_super) {
  40979. __extends(PBRBaseMaterial, _super);
  40980. /**
  40981. * Instantiates a new PBRMaterial instance.
  40982. *
  40983. * @param name The material name
  40984. * @param scene The scene the material will be use in.
  40985. */
  40986. function PBRBaseMaterial(name, scene) {
  40987. var _this = _super.call(this, name, scene) || this;
  40988. /**
  40989. * Intensity of the direct lights e.g. the four lights available in your scene.
  40990. * This impacts both the direct diffuse and specular highlights.
  40991. */
  40992. _this._directIntensity = 1.0;
  40993. /**
  40994. * Intensity of the emissive part of the material.
  40995. * This helps controlling the emissive effect without modifying the emissive color.
  40996. */
  40997. _this._emissiveIntensity = 1.0;
  40998. /**
  40999. * Intensity of the environment e.g. how much the environment will light the object
  41000. * either through harmonics for rough material or through the refelction for shiny ones.
  41001. */
  41002. _this._environmentIntensity = 1.0;
  41003. /**
  41004. * This is a special control allowing the reduction of the specular highlights coming from the
  41005. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41006. */
  41007. _this._specularIntensity = 1.0;
  41008. /**
  41009. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  41010. */
  41011. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  41012. /**
  41013. * Debug Control allowing disabling the bump map on this material.
  41014. */
  41015. _this._disableBumpMap = false;
  41016. /**
  41017. * AKA Occlusion Texture Intensity in other nomenclature.
  41018. */
  41019. _this._ambientTextureStrength = 1.0;
  41020. /**
  41021. * The color of a material in ambient lighting.
  41022. */
  41023. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  41024. /**
  41025. * AKA Diffuse Color in other nomenclature.
  41026. */
  41027. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  41028. /**
  41029. * AKA Specular Color in other nomenclature.
  41030. */
  41031. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41032. /**
  41033. * The color applied when light is reflected from a material.
  41034. */
  41035. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  41036. /**
  41037. * The color applied when light is emitted from a material.
  41038. */
  41039. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  41040. /**
  41041. * AKA Glossiness in other nomenclature.
  41042. */
  41043. _this._microSurface = 0.9;
  41044. /**
  41045. * source material index of refraction (IOR)' / 'destination material IOR.
  41046. */
  41047. _this._indexOfRefraction = 0.66;
  41048. /**
  41049. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41050. */
  41051. _this._invertRefractionY = false;
  41052. /**
  41053. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41054. * Materials half opaque for instance using refraction could benefit from this control.
  41055. */
  41056. _this._linkRefractionWithTransparency = false;
  41057. /**
  41058. * Specifies that the material will use the light map as a show map.
  41059. */
  41060. _this._useLightmapAsShadowmap = false;
  41061. /**
  41062. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41063. * makes the reflect vector face the model (under horizon).
  41064. */
  41065. _this._useHorizonOcclusion = true;
  41066. /**
  41067. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41068. * too much the area relying on ambient texture to define their ambient occlusion.
  41069. */
  41070. _this._useRadianceOcclusion = true;
  41071. /**
  41072. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41073. */
  41074. _this._useAlphaFromAlbedoTexture = false;
  41075. /**
  41076. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41077. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41078. */
  41079. _this._useSpecularOverAlpha = true;
  41080. /**
  41081. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41082. */
  41083. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  41084. /**
  41085. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41086. */
  41087. _this._useRoughnessFromMetallicTextureAlpha = true;
  41088. /**
  41089. * Specifies if the metallic texture contains the roughness information in its green channel.
  41090. */
  41091. _this._useRoughnessFromMetallicTextureGreen = false;
  41092. /**
  41093. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41094. */
  41095. _this._useMetallnessFromMetallicTextureBlue = false;
  41096. /**
  41097. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41098. */
  41099. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  41100. /**
  41101. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41102. */
  41103. _this._useAmbientInGrayScale = false;
  41104. /**
  41105. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41106. * The material will try to infer what glossiness each pixel should be.
  41107. */
  41108. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  41109. /**
  41110. * BJS is using an harcoded light falloff based on a manually sets up range.
  41111. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41112. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41113. */
  41114. _this._usePhysicalLightFalloff = true;
  41115. /**
  41116. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41117. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41118. */
  41119. _this._useRadianceOverAlpha = true;
  41120. /**
  41121. * Allows using an object space normal map (instead of tangent space).
  41122. */
  41123. _this._useObjectSpaceNormalMap = false;
  41124. /**
  41125. * Allows using the bump map in parallax mode.
  41126. */
  41127. _this._useParallax = false;
  41128. /**
  41129. * Allows using the bump map in parallax occlusion mode.
  41130. */
  41131. _this._useParallaxOcclusion = false;
  41132. /**
  41133. * Controls the scale bias of the parallax mode.
  41134. */
  41135. _this._parallaxScaleBias = 0.05;
  41136. /**
  41137. * If sets to true, disables all the lights affecting the material.
  41138. */
  41139. _this._disableLighting = false;
  41140. /**
  41141. * Number of Simultaneous lights allowed on the material.
  41142. */
  41143. _this._maxSimultaneousLights = 4;
  41144. /**
  41145. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  41146. */
  41147. _this._invertNormalMapX = false;
  41148. /**
  41149. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  41150. */
  41151. _this._invertNormalMapY = false;
  41152. /**
  41153. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41154. */
  41155. _this._twoSidedLighting = false;
  41156. /**
  41157. * Defines the alpha limits in alpha test mode.
  41158. */
  41159. _this._alphaCutOff = 0.4;
  41160. /**
  41161. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41162. */
  41163. _this._forceAlphaTest = false;
  41164. /**
  41165. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41166. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41167. */
  41168. _this._useAlphaFresnel = false;
  41169. /**
  41170. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41171. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41172. */
  41173. _this._useLinearAlphaFresnel = false;
  41174. /**
  41175. * The transparency mode of the material.
  41176. */
  41177. _this._transparencyMode = null;
  41178. /**
  41179. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  41180. * from cos thetav and roughness:
  41181. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  41182. */
  41183. _this._environmentBRDFTexture = null;
  41184. /**
  41185. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41186. */
  41187. _this._forceIrradianceInFragment = false;
  41188. /**
  41189. * Force normal to face away from face.
  41190. */
  41191. _this._forceNormalForward = false;
  41192. /**
  41193. * Stores the available render targets.
  41194. */
  41195. _this._renderTargets = new BABYLON.SmartArray(16);
  41196. /**
  41197. * Sets the global ambient color for the material used in lighting calculations.
  41198. */
  41199. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41200. /**
  41201. * If set to true, no lighting calculations will be applied.
  41202. */
  41203. _this._unlit = false;
  41204. // Setup the default processing configuration to the scene.
  41205. _this._attachImageProcessingConfiguration(null);
  41206. _this.getRenderTargetTextures = function () {
  41207. _this._renderTargets.reset();
  41208. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41209. _this._renderTargets.push(_this._reflectionTexture);
  41210. }
  41211. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41212. _this._renderTargets.push(_this._refractionTexture);
  41213. }
  41214. return _this._renderTargets;
  41215. };
  41216. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41217. return _this;
  41218. }
  41219. /**
  41220. * Attaches a new image processing configuration to the PBR Material.
  41221. * @param configuration
  41222. */
  41223. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41224. var _this = this;
  41225. if (configuration === this._imageProcessingConfiguration) {
  41226. return;
  41227. }
  41228. // Detaches observer.
  41229. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41230. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41231. }
  41232. // Pick the scene configuration if needed.
  41233. if (!configuration) {
  41234. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41235. }
  41236. else {
  41237. this._imageProcessingConfiguration = configuration;
  41238. }
  41239. // Attaches observer.
  41240. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41241. _this._markAllSubMeshesAsImageProcessingDirty();
  41242. });
  41243. };
  41244. /**
  41245. * Gets the name of the material class.
  41246. */
  41247. PBRBaseMaterial.prototype.getClassName = function () {
  41248. return "PBRBaseMaterial";
  41249. };
  41250. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  41251. /**
  41252. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41253. */
  41254. get: function () {
  41255. return this._useLogarithmicDepth;
  41256. },
  41257. /**
  41258. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41259. */
  41260. set: function (value) {
  41261. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41262. },
  41263. enumerable: true,
  41264. configurable: true
  41265. });
  41266. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  41267. /**
  41268. * Gets the current transparency mode.
  41269. */
  41270. get: function () {
  41271. return this._transparencyMode;
  41272. },
  41273. /**
  41274. * Sets the transparency mode of the material.
  41275. */
  41276. set: function (value) {
  41277. if (this._transparencyMode === value) {
  41278. return;
  41279. }
  41280. this._transparencyMode = value;
  41281. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  41282. this._markAllSubMeshesAsTexturesAndMiscDirty();
  41283. },
  41284. enumerable: true,
  41285. configurable: true
  41286. });
  41287. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  41288. /**
  41289. * Returns true if alpha blending should be disabled.
  41290. */
  41291. get: function () {
  41292. return (this._linkRefractionWithTransparency ||
  41293. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  41294. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41295. },
  41296. enumerable: true,
  41297. configurable: true
  41298. });
  41299. /**
  41300. * Specifies whether or not this material should be rendered in alpha blend mode.
  41301. */
  41302. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  41303. if (this._disableAlphaBlending) {
  41304. return false;
  41305. }
  41306. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  41307. };
  41308. /**
  41309. * Specifies if the mesh will require alpha blending.
  41310. * @param mesh - BJS mesh.
  41311. */
  41312. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  41313. if (this._disableAlphaBlending) {
  41314. return false;
  41315. }
  41316. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  41317. };
  41318. /**
  41319. * Specifies whether or not this material should be rendered in alpha test mode.
  41320. */
  41321. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  41322. if (this._forceAlphaTest) {
  41323. return true;
  41324. }
  41325. if (this._linkRefractionWithTransparency) {
  41326. return false;
  41327. }
  41328. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41329. };
  41330. /**
  41331. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  41332. */
  41333. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  41334. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  41335. };
  41336. /**
  41337. * Gets the texture used for the alpha test.
  41338. */
  41339. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  41340. return this._albedoTexture;
  41341. };
  41342. /**
  41343. * Specifies that the submesh is ready to be used.
  41344. * @param mesh - BJS mesh.
  41345. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  41346. * @param useInstances - Specifies that instances should be used.
  41347. * @returns - boolean indicating that the submesh is ready or not.
  41348. */
  41349. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41350. if (subMesh.effect && this.isFrozen) {
  41351. if (this._wasPreviouslyReady) {
  41352. return true;
  41353. }
  41354. }
  41355. if (!subMesh._materialDefines) {
  41356. subMesh._materialDefines = new PBRMaterialDefines();
  41357. }
  41358. var defines = subMesh._materialDefines;
  41359. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41360. if (defines._renderId === this.getScene().getRenderId()) {
  41361. return true;
  41362. }
  41363. }
  41364. var scene = this.getScene();
  41365. var engine = scene.getEngine();
  41366. if (defines._areTexturesDirty) {
  41367. if (scene.texturesEnabled) {
  41368. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41369. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  41370. return false;
  41371. }
  41372. }
  41373. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41374. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41375. return false;
  41376. }
  41377. }
  41378. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41379. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41380. return false;
  41381. }
  41382. }
  41383. var reflectionTexture = this._getReflectionTexture();
  41384. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41385. if (!reflectionTexture.isReadyOrNotBlocking()) {
  41386. return false;
  41387. }
  41388. }
  41389. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41390. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41391. return false;
  41392. }
  41393. }
  41394. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41395. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41396. return false;
  41397. }
  41398. }
  41399. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41400. if (this._metallicTexture) {
  41401. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  41402. return false;
  41403. }
  41404. }
  41405. else if (this._reflectivityTexture) {
  41406. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  41407. return false;
  41408. }
  41409. }
  41410. if (this._microSurfaceTexture) {
  41411. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  41412. return false;
  41413. }
  41414. }
  41415. }
  41416. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41417. // Bump texture cannot be not blocking.
  41418. if (!this._bumpTexture.isReady()) {
  41419. return false;
  41420. }
  41421. }
  41422. var refractionTexture = this._getRefractionTexture();
  41423. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41424. if (!refractionTexture.isReadyOrNotBlocking()) {
  41425. return false;
  41426. }
  41427. }
  41428. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41429. // This is blocking.
  41430. if (!this._environmentBRDFTexture.isReady()) {
  41431. return false;
  41432. }
  41433. }
  41434. }
  41435. }
  41436. if (defines._areImageProcessingDirty) {
  41437. if (!this._imageProcessingConfiguration.isReady()) {
  41438. return false;
  41439. }
  41440. }
  41441. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41442. mesh.createNormals(true);
  41443. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  41444. }
  41445. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  41446. if (effect) {
  41447. scene.resetCachedMaterial();
  41448. subMesh.setEffect(effect, defines);
  41449. this.buildUniformLayout();
  41450. }
  41451. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41452. return false;
  41453. }
  41454. defines._renderId = scene.getRenderId();
  41455. this._wasPreviouslyReady = true;
  41456. return true;
  41457. };
  41458. /**
  41459. * Specifies if the material uses metallic roughness workflow.
  41460. * @returns boolean specifiying if the material uses metallic roughness workflow.
  41461. */
  41462. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  41463. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  41464. return true;
  41465. }
  41466. return false;
  41467. };
  41468. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  41469. if (onCompiled === void 0) { onCompiled = null; }
  41470. if (onError === void 0) { onError = null; }
  41471. if (useInstances === void 0) { useInstances = null; }
  41472. if (useClipPlane === void 0) { useClipPlane = null; }
  41473. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  41474. if (!defines.isDirty) {
  41475. return null;
  41476. }
  41477. defines.markAsProcessed();
  41478. var scene = this.getScene();
  41479. var engine = scene.getEngine();
  41480. // Fallbacks
  41481. var fallbacks = new BABYLON.EffectFallbacks();
  41482. var fallbackRank = 0;
  41483. if (defines.USESPHERICALINVERTEX) {
  41484. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  41485. }
  41486. if (defines.FOG) {
  41487. fallbacks.addFallback(fallbackRank, "FOG");
  41488. }
  41489. if (defines.POINTSIZE) {
  41490. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  41491. }
  41492. if (defines.LOGARITHMICDEPTH) {
  41493. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  41494. }
  41495. if (defines.PARALLAX) {
  41496. fallbacks.addFallback(fallbackRank, "PARALLAX");
  41497. }
  41498. if (defines.PARALLAXOCCLUSION) {
  41499. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  41500. }
  41501. if (defines.ENVIRONMENTBRDF) {
  41502. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  41503. }
  41504. if (defines.TANGENT) {
  41505. fallbacks.addFallback(fallbackRank++, "TANGENT");
  41506. }
  41507. if (defines.BUMP) {
  41508. fallbacks.addFallback(fallbackRank++, "BUMP");
  41509. }
  41510. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  41511. if (defines.SPECULARTERM) {
  41512. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  41513. }
  41514. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  41515. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  41516. }
  41517. if (defines.LIGHTMAP) {
  41518. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  41519. }
  41520. if (defines.NORMAL) {
  41521. fallbacks.addFallback(fallbackRank++, "NORMAL");
  41522. }
  41523. if (defines.AMBIENT) {
  41524. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  41525. }
  41526. if (defines.EMISSIVE) {
  41527. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  41528. }
  41529. if (defines.VERTEXCOLOR) {
  41530. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  41531. }
  41532. if (defines.NUM_BONE_INFLUENCERS > 0) {
  41533. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  41534. }
  41535. if (defines.MORPHTARGETS) {
  41536. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  41537. }
  41538. //Attributes
  41539. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41540. if (defines.NORMAL) {
  41541. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41542. }
  41543. if (defines.TANGENT) {
  41544. attribs.push(BABYLON.VertexBuffer.TangentKind);
  41545. }
  41546. if (defines.UV1) {
  41547. attribs.push(BABYLON.VertexBuffer.UVKind);
  41548. }
  41549. if (defines.UV2) {
  41550. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41551. }
  41552. if (defines.VERTEXCOLOR) {
  41553. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41554. }
  41555. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41556. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41557. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41558. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  41559. "vFogInfos", "vFogColor", "pointSize",
  41560. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  41561. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41562. "mBones",
  41563. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  41564. "vLightingIntensity",
  41565. "logarithmicDepthConstant",
  41566. "vSphericalX", "vSphericalY", "vSphericalZ",
  41567. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  41568. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  41569. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  41570. "vTangentSpaceParams"
  41571. ];
  41572. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  41573. "bumpSampler", "lightmapSampler", "opacitySampler",
  41574. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  41575. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  41576. "microSurfaceSampler", "environmentBrdfSampler"];
  41577. var uniformBuffers = ["Material", "Scene"];
  41578. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41579. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41580. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41581. uniformsNames: uniforms,
  41582. uniformBuffersNames: uniformBuffers,
  41583. samplers: samplers,
  41584. defines: defines,
  41585. maxSimultaneousLights: this._maxSimultaneousLights
  41586. });
  41587. var join = defines.toString();
  41588. return engine.createEffect("pbr", {
  41589. attributes: attribs,
  41590. uniformsNames: uniforms,
  41591. uniformBuffersNames: uniformBuffers,
  41592. samplers: samplers,
  41593. defines: join,
  41594. fallbacks: fallbacks,
  41595. onCompiled: onCompiled,
  41596. onError: onError,
  41597. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41598. }, engine);
  41599. };
  41600. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  41601. if (useInstances === void 0) { useInstances = null; }
  41602. if (useClipPlane === void 0) { useClipPlane = null; }
  41603. var scene = this.getScene();
  41604. var engine = scene.getEngine();
  41605. // Lights
  41606. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41607. defines._needNormals = true;
  41608. // Textures
  41609. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  41610. if (defines._areTexturesDirty) {
  41611. defines._needUVs = false;
  41612. if (scene.texturesEnabled) {
  41613. if (scene.getEngine().getCaps().textureLOD) {
  41614. defines.LODBASEDMICROSFURACE = true;
  41615. }
  41616. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41617. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  41618. }
  41619. else {
  41620. defines.ALBEDO = false;
  41621. }
  41622. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41623. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41624. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41625. }
  41626. else {
  41627. defines.AMBIENT = false;
  41628. }
  41629. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41630. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41631. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41632. }
  41633. else {
  41634. defines.OPACITY = false;
  41635. }
  41636. var reflectionTexture = this._getReflectionTexture();
  41637. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41638. defines.REFLECTION = true;
  41639. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41640. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41641. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41642. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41643. defines.INVERTCUBICMAP = true;
  41644. }
  41645. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41646. switch (reflectionTexture.coordinatesMode) {
  41647. case BABYLON.Texture.CUBIC_MODE:
  41648. case BABYLON.Texture.INVCUBIC_MODE:
  41649. defines.REFLECTIONMAP_CUBIC = true;
  41650. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41651. break;
  41652. case BABYLON.Texture.EXPLICIT_MODE:
  41653. defines.REFLECTIONMAP_EXPLICIT = true;
  41654. break;
  41655. case BABYLON.Texture.PLANAR_MODE:
  41656. defines.REFLECTIONMAP_PLANAR = true;
  41657. break;
  41658. case BABYLON.Texture.PROJECTION_MODE:
  41659. defines.REFLECTIONMAP_PROJECTION = true;
  41660. break;
  41661. case BABYLON.Texture.SKYBOX_MODE:
  41662. defines.REFLECTIONMAP_SKYBOX = true;
  41663. break;
  41664. case BABYLON.Texture.SPHERICAL_MODE:
  41665. defines.REFLECTIONMAP_SPHERICAL = true;
  41666. break;
  41667. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41668. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41669. break;
  41670. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41671. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41672. break;
  41673. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41674. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41675. break;
  41676. }
  41677. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41678. if (reflectionTexture.sphericalPolynomial) {
  41679. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41680. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41681. defines.USESPHERICALINVERTEX = false;
  41682. }
  41683. else {
  41684. defines.USESPHERICALINVERTEX = true;
  41685. }
  41686. }
  41687. }
  41688. }
  41689. else {
  41690. defines.REFLECTION = false;
  41691. defines.REFLECTIONMAP_3D = false;
  41692. defines.REFLECTIONMAP_SPHERICAL = false;
  41693. defines.REFLECTIONMAP_PLANAR = false;
  41694. defines.REFLECTIONMAP_CUBIC = false;
  41695. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41696. defines.REFLECTIONMAP_PROJECTION = false;
  41697. defines.REFLECTIONMAP_SKYBOX = false;
  41698. defines.REFLECTIONMAP_EXPLICIT = false;
  41699. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41700. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41701. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41702. defines.INVERTCUBICMAP = false;
  41703. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41704. defines.USESPHERICALINVERTEX = false;
  41705. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41706. defines.LODINREFLECTIONALPHA = false;
  41707. defines.GAMMAREFLECTION = false;
  41708. }
  41709. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41710. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41711. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41712. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  41713. }
  41714. else {
  41715. defines.LIGHTMAP = false;
  41716. }
  41717. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41718. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41719. }
  41720. else {
  41721. defines.EMISSIVE = false;
  41722. }
  41723. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41724. if (this._metallicTexture) {
  41725. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41726. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41727. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41728. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41729. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41730. }
  41731. else if (this._reflectivityTexture) {
  41732. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41733. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41734. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41735. }
  41736. else {
  41737. defines.REFLECTIVITY = false;
  41738. }
  41739. if (this._microSurfaceTexture) {
  41740. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41741. }
  41742. else {
  41743. defines.MICROSURFACEMAP = false;
  41744. }
  41745. }
  41746. else {
  41747. defines.REFLECTIVITY = false;
  41748. defines.MICROSURFACEMAP = false;
  41749. }
  41750. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41751. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41752. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41753. defines.PARALLAX = true;
  41754. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41755. }
  41756. else {
  41757. defines.PARALLAX = false;
  41758. }
  41759. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41760. }
  41761. else {
  41762. defines.BUMP = false;
  41763. }
  41764. var refractionTexture = this._getRefractionTexture();
  41765. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41766. defines.REFRACTION = true;
  41767. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41768. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41769. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41770. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41771. if (this._linkRefractionWithTransparency) {
  41772. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41773. }
  41774. }
  41775. else {
  41776. defines.REFRACTION = false;
  41777. }
  41778. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41779. defines.ENVIRONMENTBRDF = true;
  41780. }
  41781. else {
  41782. defines.ENVIRONMENTBRDF = false;
  41783. }
  41784. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41785. defines.ALPHAFROMALBEDO = true;
  41786. }
  41787. else {
  41788. defines.ALPHAFROMALBEDO = false;
  41789. }
  41790. }
  41791. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41792. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41793. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41794. if (!this.backFaceCulling && this._twoSidedLighting) {
  41795. defines.TWOSIDEDLIGHTING = true;
  41796. }
  41797. else {
  41798. defines.TWOSIDEDLIGHTING = false;
  41799. }
  41800. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  41801. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41802. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41803. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41804. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41805. }
  41806. if (defines._areImageProcessingDirty) {
  41807. this._imageProcessingConfiguration.prepareDefines(defines);
  41808. }
  41809. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41810. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41811. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41812. // Misc.
  41813. if (defines._areMiscDirty) {
  41814. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41815. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41816. }
  41817. // Values that need to be evaluated on every frame
  41818. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41819. // Attribs
  41820. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41821. };
  41822. /**
  41823. * Force shader compilation
  41824. */
  41825. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41826. var _this = this;
  41827. var localOptions = __assign({ clipPlane: false }, options);
  41828. var defines = new PBRMaterialDefines();
  41829. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41830. if (effect.isReady()) {
  41831. if (onCompiled) {
  41832. onCompiled(this);
  41833. }
  41834. }
  41835. else {
  41836. effect.onCompileObservable.add(function () {
  41837. if (onCompiled) {
  41838. onCompiled(_this);
  41839. }
  41840. });
  41841. }
  41842. };
  41843. /**
  41844. * Initializes the uniform buffer layout for the shader.
  41845. */
  41846. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41847. // Order is important !
  41848. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41849. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41850. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41851. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41852. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41853. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41854. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41855. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41856. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41857. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41858. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41859. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41860. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41861. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41862. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41863. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41864. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41865. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41866. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41867. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41868. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41869. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41870. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41871. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41872. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41873. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41874. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41875. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41876. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41877. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41878. this._uniformBuffer.addUniform("pointSize", 1);
  41879. this._uniformBuffer.create();
  41880. };
  41881. /**
  41882. * Unbinds the textures.
  41883. */
  41884. PBRBaseMaterial.prototype.unbind = function () {
  41885. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41886. this._uniformBuffer.setTexture("reflectionSampler", null);
  41887. }
  41888. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41889. this._uniformBuffer.setTexture("refractionSampler", null);
  41890. }
  41891. _super.prototype.unbind.call(this);
  41892. };
  41893. /**
  41894. * Binds the submesh data.
  41895. * @param world - The world matrix.
  41896. * @param mesh - The BJS mesh.
  41897. * @param subMesh - A submesh of the BJS mesh.
  41898. */
  41899. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41900. var scene = this.getScene();
  41901. var defines = subMesh._materialDefines;
  41902. if (!defines) {
  41903. return;
  41904. }
  41905. var effect = subMesh.effect;
  41906. if (!effect) {
  41907. return;
  41908. }
  41909. this._activeEffect = effect;
  41910. // Matrices
  41911. this.bindOnlyWorldMatrix(world);
  41912. // Normal Matrix
  41913. if (defines.OBJECTSPACE_NORMALMAP) {
  41914. world.toNormalMatrix(this._normalMatrix);
  41915. this.bindOnlyNormalMatrix(this._normalMatrix);
  41916. }
  41917. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41918. // Bones
  41919. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41920. var reflectionTexture = null;
  41921. if (mustRebind) {
  41922. this._uniformBuffer.bindToEffect(effect, "Material");
  41923. this.bindViewProjection(effect);
  41924. reflectionTexture = this._getReflectionTexture();
  41925. var refractionTexture = this._getRefractionTexture();
  41926. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41927. // Texture uniforms
  41928. if (scene.texturesEnabled) {
  41929. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41930. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41931. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41932. }
  41933. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41934. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41935. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41936. }
  41937. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41938. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41939. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41940. }
  41941. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41942. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  41943. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  41944. if (reflectionTexture.boundingBoxSize) {
  41945. var cubeTexture = reflectionTexture;
  41946. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41947. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41948. }
  41949. var polynomials = reflectionTexture.sphericalPolynomial;
  41950. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  41951. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  41952. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  41953. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  41954. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  41955. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  41956. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  41957. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  41958. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  41959. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  41960. }
  41961. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  41962. }
  41963. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41964. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41965. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41966. }
  41967. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41968. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41969. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41970. }
  41971. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41972. if (this._metallicTexture) {
  41973. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  41974. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  41975. }
  41976. else if (this._reflectivityTexture) {
  41977. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  41978. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  41979. }
  41980. if (this._microSurfaceTexture) {
  41981. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  41982. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  41983. }
  41984. }
  41985. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41986. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  41987. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  41988. if (scene._mirroredCameraPosition) {
  41989. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  41990. }
  41991. else {
  41992. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  41993. }
  41994. }
  41995. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41996. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  41997. var depth = 1.0;
  41998. if (!refractionTexture.isCube) {
  41999. if (refractionTexture.depth) {
  42000. depth = refractionTexture.depth;
  42001. }
  42002. }
  42003. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  42004. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  42005. }
  42006. }
  42007. // Point size
  42008. if (this.pointsCloud) {
  42009. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42010. }
  42011. // Colors
  42012. if (defines.METALLICWORKFLOW) {
  42013. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  42014. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  42015. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  42016. }
  42017. else {
  42018. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  42019. }
  42020. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  42021. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  42022. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  42023. // Misc
  42024. this._lightingInfos.x = this._directIntensity;
  42025. this._lightingInfos.y = this._emissiveIntensity;
  42026. this._lightingInfos.z = this._environmentIntensity;
  42027. this._lightingInfos.w = this._specularIntensity;
  42028. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  42029. }
  42030. // Textures
  42031. if (scene.texturesEnabled) {
  42032. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  42033. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  42034. }
  42035. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  42036. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  42037. }
  42038. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  42039. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  42040. }
  42041. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  42042. if (defines.LODBASEDMICROSFURACE) {
  42043. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  42044. }
  42045. else {
  42046. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  42047. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  42048. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  42049. }
  42050. }
  42051. if (defines.ENVIRONMENTBRDF) {
  42052. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  42053. }
  42054. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42055. if (defines.LODBASEDMICROSFURACE) {
  42056. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  42057. }
  42058. else {
  42059. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  42060. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  42061. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  42062. }
  42063. }
  42064. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  42065. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  42066. }
  42067. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  42068. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  42069. }
  42070. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42071. if (this._metallicTexture) {
  42072. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  42073. }
  42074. else if (this._reflectivityTexture) {
  42075. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  42076. }
  42077. if (this._microSurfaceTexture) {
  42078. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  42079. }
  42080. }
  42081. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42082. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  42083. }
  42084. }
  42085. // Clip plane
  42086. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  42087. // Colors
  42088. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  42089. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42090. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  42091. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  42092. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42093. }
  42094. if (mustRebind || !this.isFrozen) {
  42095. // Lights
  42096. if (scene.lightsEnabled && !this._disableLighting) {
  42097. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  42098. }
  42099. // View
  42100. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  42101. this.bindView(effect);
  42102. }
  42103. // Fog
  42104. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  42105. // Morph targets
  42106. if (defines.NUM_MORPH_INFLUENCERS) {
  42107. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  42108. }
  42109. // image processing
  42110. this._imageProcessingConfiguration.bind(this._activeEffect);
  42111. // Log. depth
  42112. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  42113. }
  42114. this._uniformBuffer.update();
  42115. this._afterBind(mesh);
  42116. };
  42117. /**
  42118. * Returns the animatable textures.
  42119. * @returns - Array of animatable textures.
  42120. */
  42121. PBRBaseMaterial.prototype.getAnimatables = function () {
  42122. var results = [];
  42123. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  42124. results.push(this._albedoTexture);
  42125. }
  42126. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42127. results.push(this._ambientTexture);
  42128. }
  42129. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42130. results.push(this._opacityTexture);
  42131. }
  42132. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42133. results.push(this._reflectionTexture);
  42134. }
  42135. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42136. results.push(this._emissiveTexture);
  42137. }
  42138. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  42139. results.push(this._metallicTexture);
  42140. }
  42141. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  42142. results.push(this._reflectivityTexture);
  42143. }
  42144. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42145. results.push(this._bumpTexture);
  42146. }
  42147. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42148. results.push(this._lightmapTexture);
  42149. }
  42150. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42151. results.push(this._refractionTexture);
  42152. }
  42153. return results;
  42154. };
  42155. /**
  42156. * Returns the texture used for reflections.
  42157. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  42158. */
  42159. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  42160. if (this._reflectionTexture) {
  42161. return this._reflectionTexture;
  42162. }
  42163. return this.getScene().environmentTexture;
  42164. };
  42165. /**
  42166. * Returns the texture used for refraction or null if none is used.
  42167. * @returns - Refection texture if present. If no refraction texture and refraction
  42168. * is linked with transparency, returns environment texture. Otherwise, returns null.
  42169. */
  42170. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  42171. if (this._refractionTexture) {
  42172. return this._refractionTexture;
  42173. }
  42174. if (this._linkRefractionWithTransparency) {
  42175. return this.getScene().environmentTexture;
  42176. }
  42177. return null;
  42178. };
  42179. /**
  42180. * Disposes the resources of the material.
  42181. * @param forceDisposeEffect - Forces the disposal of effects.
  42182. * @param forceDisposeTextures - Forces the disposal of all textures.
  42183. */
  42184. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42185. if (forceDisposeTextures) {
  42186. if (this._albedoTexture) {
  42187. this._albedoTexture.dispose();
  42188. }
  42189. if (this._ambientTexture) {
  42190. this._ambientTexture.dispose();
  42191. }
  42192. if (this._opacityTexture) {
  42193. this._opacityTexture.dispose();
  42194. }
  42195. if (this._reflectionTexture) {
  42196. this._reflectionTexture.dispose();
  42197. }
  42198. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  42199. this._environmentBRDFTexture.dispose();
  42200. }
  42201. if (this._emissiveTexture) {
  42202. this._emissiveTexture.dispose();
  42203. }
  42204. if (this._metallicTexture) {
  42205. this._metallicTexture.dispose();
  42206. }
  42207. if (this._reflectivityTexture) {
  42208. this._reflectivityTexture.dispose();
  42209. }
  42210. if (this._bumpTexture) {
  42211. this._bumpTexture.dispose();
  42212. }
  42213. if (this._lightmapTexture) {
  42214. this._lightmapTexture.dispose();
  42215. }
  42216. if (this._refractionTexture) {
  42217. this._refractionTexture.dispose();
  42218. }
  42219. }
  42220. this._renderTargets.dispose();
  42221. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42222. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42223. }
  42224. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42225. };
  42226. /**
  42227. * Stores the reflectivity values based on metallic roughness workflow.
  42228. */
  42229. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  42230. __decorate([
  42231. BABYLON.serializeAsImageProcessingConfiguration()
  42232. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  42233. __decorate([
  42234. BABYLON.serialize()
  42235. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  42236. __decorate([
  42237. BABYLON.serialize()
  42238. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  42239. return PBRBaseMaterial;
  42240. }(BABYLON.PushMaterial));
  42241. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  42242. })(BABYLON || (BABYLON = {}));
  42243. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  42244. "use strict";
  42245. var BABYLON;
  42246. (function (BABYLON) {
  42247. /**
  42248. * The Physically based simple base material of BJS.
  42249. *
  42250. * This enables better naming and convention enforcements on top of the pbrMaterial.
  42251. * It is used as the base class for both the specGloss and metalRough conventions.
  42252. */
  42253. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  42254. __extends(PBRBaseSimpleMaterial, _super);
  42255. /**
  42256. * Instantiates a new PBRMaterial instance.
  42257. *
  42258. * @param name The material name
  42259. * @param scene The scene the material will be use in.
  42260. */
  42261. function PBRBaseSimpleMaterial(name, scene) {
  42262. var _this = _super.call(this, name, scene) || this;
  42263. /**
  42264. * Number of Simultaneous lights allowed on the material.
  42265. */
  42266. _this.maxSimultaneousLights = 4;
  42267. /**
  42268. * If sets to true, disables all the lights affecting the material.
  42269. */
  42270. _this.disableLighting = false;
  42271. /**
  42272. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42273. */
  42274. _this.invertNormalMapX = false;
  42275. /**
  42276. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42277. */
  42278. _this.invertNormalMapY = false;
  42279. /**
  42280. * Emissivie color used to self-illuminate the model.
  42281. */
  42282. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42283. /**
  42284. * Occlusion Channel Strenght.
  42285. */
  42286. _this.occlusionStrength = 1.0;
  42287. _this.useLightmapAsShadowmap = false;
  42288. _this._useAlphaFromAlbedoTexture = true;
  42289. _this._useAmbientInGrayScale = true;
  42290. return _this;
  42291. }
  42292. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  42293. /**
  42294. * Gets the current double sided mode.
  42295. */
  42296. get: function () {
  42297. return this._twoSidedLighting;
  42298. },
  42299. /**
  42300. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42301. */
  42302. set: function (value) {
  42303. if (this._twoSidedLighting === value) {
  42304. return;
  42305. }
  42306. this._twoSidedLighting = value;
  42307. this.backFaceCulling = !value;
  42308. this._markAllSubMeshesAsTexturesDirty();
  42309. },
  42310. enumerable: true,
  42311. configurable: true
  42312. });
  42313. /**
  42314. * Return the active textures of the material.
  42315. */
  42316. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  42317. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42318. if (this.environmentTexture) {
  42319. activeTextures.push(this.environmentTexture);
  42320. }
  42321. if (this.normalTexture) {
  42322. activeTextures.push(this.normalTexture);
  42323. }
  42324. if (this.emissiveTexture) {
  42325. activeTextures.push(this.emissiveTexture);
  42326. }
  42327. if (this.occlusionTexture) {
  42328. activeTextures.push(this.occlusionTexture);
  42329. }
  42330. if (this.lightmapTexture) {
  42331. activeTextures.push(this.lightmapTexture);
  42332. }
  42333. return activeTextures;
  42334. };
  42335. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  42336. if (_super.prototype.hasTexture.call(this, texture)) {
  42337. return true;
  42338. }
  42339. if (this.lightmapTexture === texture) {
  42340. return true;
  42341. }
  42342. return false;
  42343. };
  42344. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  42345. return "PBRBaseSimpleMaterial";
  42346. };
  42347. __decorate([
  42348. BABYLON.serialize(),
  42349. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42350. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  42351. __decorate([
  42352. BABYLON.serialize(),
  42353. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42354. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  42355. __decorate([
  42356. BABYLON.serializeAsTexture(),
  42357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  42358. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  42359. __decorate([
  42360. BABYLON.serialize(),
  42361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42362. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  42363. __decorate([
  42364. BABYLON.serialize(),
  42365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42366. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  42367. __decorate([
  42368. BABYLON.serializeAsTexture(),
  42369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  42370. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  42371. __decorate([
  42372. BABYLON.serializeAsColor3("emissive"),
  42373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42374. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  42375. __decorate([
  42376. BABYLON.serializeAsTexture(),
  42377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42378. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  42379. __decorate([
  42380. BABYLON.serialize(),
  42381. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  42382. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  42383. __decorate([
  42384. BABYLON.serializeAsTexture(),
  42385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  42386. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  42387. __decorate([
  42388. BABYLON.serialize(),
  42389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  42390. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  42391. __decorate([
  42392. BABYLON.serialize()
  42393. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  42394. __decorate([
  42395. BABYLON.serializeAsTexture(),
  42396. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42397. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  42398. __decorate([
  42399. BABYLON.serialize(),
  42400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42401. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42402. return PBRBaseSimpleMaterial;
  42403. }(BABYLON.PBRBaseMaterial));
  42404. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  42405. })(BABYLON || (BABYLON = {}));
  42406. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  42407. "use strict";
  42408. var BABYLON;
  42409. (function (BABYLON) {
  42410. /**
  42411. * The Physically based material of BJS.
  42412. *
  42413. * This offers the main features of a standard PBR material.
  42414. * For more information, please refer to the documentation :
  42415. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  42416. */
  42417. var PBRMaterial = /** @class */ (function (_super) {
  42418. __extends(PBRMaterial, _super);
  42419. /**
  42420. * Instantiates a new PBRMaterial instance.
  42421. *
  42422. * @param name The material name
  42423. * @param scene The scene the material will be use in.
  42424. */
  42425. function PBRMaterial(name, scene) {
  42426. var _this = _super.call(this, name, scene) || this;
  42427. /**
  42428. * Intensity of the direct lights e.g. the four lights available in your scene.
  42429. * This impacts both the direct diffuse and specular highlights.
  42430. */
  42431. _this.directIntensity = 1.0;
  42432. /**
  42433. * Intensity of the emissive part of the material.
  42434. * This helps controlling the emissive effect without modifying the emissive color.
  42435. */
  42436. _this.emissiveIntensity = 1.0;
  42437. /**
  42438. * Intensity of the environment e.g. how much the environment will light the object
  42439. * either through harmonics for rough material or through the refelction for shiny ones.
  42440. */
  42441. _this.environmentIntensity = 1.0;
  42442. /**
  42443. * This is a special control allowing the reduction of the specular highlights coming from the
  42444. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  42445. */
  42446. _this.specularIntensity = 1.0;
  42447. /**
  42448. * Debug Control allowing disabling the bump map on this material.
  42449. */
  42450. _this.disableBumpMap = false;
  42451. /**
  42452. * AKA Occlusion Texture Intensity in other nomenclature.
  42453. */
  42454. _this.ambientTextureStrength = 1.0;
  42455. /**
  42456. * The color of a material in ambient lighting.
  42457. */
  42458. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42459. /**
  42460. * AKA Diffuse Color in other nomenclature.
  42461. */
  42462. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  42463. /**
  42464. * AKA Specular Color in other nomenclature.
  42465. */
  42466. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  42467. /**
  42468. * The color reflected from the material.
  42469. */
  42470. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  42471. /**
  42472. * The color emitted from the material.
  42473. */
  42474. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42475. /**
  42476. * AKA Glossiness in other nomenclature.
  42477. */
  42478. _this.microSurface = 1.0;
  42479. /**
  42480. * source material index of refraction (IOR)' / 'destination material IOR.
  42481. */
  42482. _this.indexOfRefraction = 0.66;
  42483. /**
  42484. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  42485. */
  42486. _this.invertRefractionY = false;
  42487. /**
  42488. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  42489. * Materials half opaque for instance using refraction could benefit from this control.
  42490. */
  42491. _this.linkRefractionWithTransparency = false;
  42492. _this.useLightmapAsShadowmap = false;
  42493. /**
  42494. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  42495. */
  42496. _this.useAlphaFromAlbedoTexture = false;
  42497. /**
  42498. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  42499. */
  42500. _this.forceAlphaTest = false;
  42501. /**
  42502. * Defines the alpha limits in alpha test mode.
  42503. */
  42504. _this.alphaCutOff = 0.4;
  42505. /**
  42506. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  42507. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  42508. */
  42509. _this.useSpecularOverAlpha = true;
  42510. /**
  42511. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  42512. */
  42513. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  42514. /**
  42515. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  42516. */
  42517. _this.useRoughnessFromMetallicTextureAlpha = true;
  42518. /**
  42519. * Specifies if the metallic texture contains the roughness information in its green channel.
  42520. */
  42521. _this.useRoughnessFromMetallicTextureGreen = false;
  42522. /**
  42523. * Specifies if the metallic texture contains the metallness information in its blue channel.
  42524. */
  42525. _this.useMetallnessFromMetallicTextureBlue = false;
  42526. /**
  42527. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  42528. */
  42529. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  42530. /**
  42531. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  42532. */
  42533. _this.useAmbientInGrayScale = false;
  42534. /**
  42535. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  42536. * The material will try to infer what glossiness each pixel should be.
  42537. */
  42538. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  42539. /**
  42540. * BJS is using an harcoded light falloff based on a manually sets up range.
  42541. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  42542. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  42543. */
  42544. _this.usePhysicalLightFalloff = true;
  42545. /**
  42546. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  42547. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  42548. */
  42549. _this.useRadianceOverAlpha = true;
  42550. /**
  42551. * Allows using an object space normal map (instead of tangent space).
  42552. */
  42553. _this.useObjectSpaceNormalMap = false;
  42554. /**
  42555. * Allows using the bump map in parallax mode.
  42556. */
  42557. _this.useParallax = false;
  42558. /**
  42559. * Allows using the bump map in parallax occlusion mode.
  42560. */
  42561. _this.useParallaxOcclusion = false;
  42562. /**
  42563. * Controls the scale bias of the parallax mode.
  42564. */
  42565. _this.parallaxScaleBias = 0.05;
  42566. /**
  42567. * If sets to true, disables all the lights affecting the material.
  42568. */
  42569. _this.disableLighting = false;
  42570. /**
  42571. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  42572. */
  42573. _this.forceIrradianceInFragment = false;
  42574. /**
  42575. * Number of Simultaneous lights allowed on the material.
  42576. */
  42577. _this.maxSimultaneousLights = 4;
  42578. /**
  42579. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42580. */
  42581. _this.invertNormalMapX = false;
  42582. /**
  42583. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42584. */
  42585. _this.invertNormalMapY = false;
  42586. /**
  42587. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42588. */
  42589. _this.twoSidedLighting = false;
  42590. /**
  42591. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42592. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  42593. */
  42594. _this.useAlphaFresnel = false;
  42595. /**
  42596. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42597. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  42598. */
  42599. _this.useLinearAlphaFresnel = false;
  42600. /**
  42601. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42602. * And/Or occlude the blended part.
  42603. */
  42604. _this.environmentBRDFTexture = null;
  42605. /**
  42606. * Force normal to face away from face.
  42607. */
  42608. _this.forceNormalForward = false;
  42609. /**
  42610. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42611. * makes the reflect vector face the model (under horizon).
  42612. */
  42613. _this.useHorizonOcclusion = true;
  42614. /**
  42615. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42616. * too much the area relying on ambient texture to define their ambient occlusion.
  42617. */
  42618. _this.useRadianceOcclusion = true;
  42619. /**
  42620. * If set to true, no lighting calculations will be applied.
  42621. */
  42622. _this.unlit = false;
  42623. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42624. return _this;
  42625. }
  42626. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42627. /**
  42628. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42629. */
  42630. get: function () {
  42631. return this._PBRMATERIAL_OPAQUE;
  42632. },
  42633. enumerable: true,
  42634. configurable: true
  42635. });
  42636. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42637. /**
  42638. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42639. */
  42640. get: function () {
  42641. return this._PBRMATERIAL_ALPHATEST;
  42642. },
  42643. enumerable: true,
  42644. configurable: true
  42645. });
  42646. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42647. /**
  42648. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42649. */
  42650. get: function () {
  42651. return this._PBRMATERIAL_ALPHABLEND;
  42652. },
  42653. enumerable: true,
  42654. configurable: true
  42655. });
  42656. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42657. /**
  42658. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42659. * They are also discarded below the alpha cutoff threshold to improve performances.
  42660. */
  42661. get: function () {
  42662. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42663. },
  42664. enumerable: true,
  42665. configurable: true
  42666. });
  42667. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42668. /**
  42669. * Gets the image processing configuration used either in this material.
  42670. */
  42671. get: function () {
  42672. return this._imageProcessingConfiguration;
  42673. },
  42674. /**
  42675. * Sets the Default image processing configuration used either in the this material.
  42676. *
  42677. * If sets to null, the scene one is in use.
  42678. */
  42679. set: function (value) {
  42680. this._attachImageProcessingConfiguration(value);
  42681. // Ensure the effect will be rebuilt.
  42682. this._markAllSubMeshesAsTexturesDirty();
  42683. },
  42684. enumerable: true,
  42685. configurable: true
  42686. });
  42687. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42688. /**
  42689. * Gets wether the color curves effect is enabled.
  42690. */
  42691. get: function () {
  42692. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42693. },
  42694. /**
  42695. * Sets wether the color curves effect is enabled.
  42696. */
  42697. set: function (value) {
  42698. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42699. },
  42700. enumerable: true,
  42701. configurable: true
  42702. });
  42703. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42704. /**
  42705. * Gets wether the color grading effect is enabled.
  42706. */
  42707. get: function () {
  42708. return this.imageProcessingConfiguration.colorGradingEnabled;
  42709. },
  42710. /**
  42711. * Gets wether the color grading effect is enabled.
  42712. */
  42713. set: function (value) {
  42714. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42715. },
  42716. enumerable: true,
  42717. configurable: true
  42718. });
  42719. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42720. /**
  42721. * Gets wether tonemapping is enabled or not.
  42722. */
  42723. get: function () {
  42724. return this._imageProcessingConfiguration.toneMappingEnabled;
  42725. },
  42726. /**
  42727. * Sets wether tonemapping is enabled or not
  42728. */
  42729. set: function (value) {
  42730. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42731. },
  42732. enumerable: true,
  42733. configurable: true
  42734. });
  42735. ;
  42736. ;
  42737. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42738. /**
  42739. * The camera exposure used on this material.
  42740. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42741. * This corresponds to a photographic exposure.
  42742. */
  42743. get: function () {
  42744. return this._imageProcessingConfiguration.exposure;
  42745. },
  42746. /**
  42747. * The camera exposure used on this material.
  42748. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42749. * This corresponds to a photographic exposure.
  42750. */
  42751. set: function (value) {
  42752. this._imageProcessingConfiguration.exposure = value;
  42753. },
  42754. enumerable: true,
  42755. configurable: true
  42756. });
  42757. ;
  42758. ;
  42759. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42760. /**
  42761. * Gets The camera contrast used on this material.
  42762. */
  42763. get: function () {
  42764. return this._imageProcessingConfiguration.contrast;
  42765. },
  42766. /**
  42767. * Sets The camera contrast used on this material.
  42768. */
  42769. set: function (value) {
  42770. this._imageProcessingConfiguration.contrast = value;
  42771. },
  42772. enumerable: true,
  42773. configurable: true
  42774. });
  42775. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42776. /**
  42777. * Gets the Color Grading 2D Lookup Texture.
  42778. */
  42779. get: function () {
  42780. return this._imageProcessingConfiguration.colorGradingTexture;
  42781. },
  42782. /**
  42783. * Sets the Color Grading 2D Lookup Texture.
  42784. */
  42785. set: function (value) {
  42786. this._imageProcessingConfiguration.colorGradingTexture = value;
  42787. },
  42788. enumerable: true,
  42789. configurable: true
  42790. });
  42791. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42792. /**
  42793. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42794. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42795. * 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;
  42796. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42797. */
  42798. get: function () {
  42799. return this._imageProcessingConfiguration.colorCurves;
  42800. },
  42801. /**
  42802. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42803. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42804. * 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;
  42805. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42806. */
  42807. set: function (value) {
  42808. this._imageProcessingConfiguration.colorCurves = value;
  42809. },
  42810. enumerable: true,
  42811. configurable: true
  42812. });
  42813. /**
  42814. * Returns the name of this material class.
  42815. */
  42816. PBRMaterial.prototype.getClassName = function () {
  42817. return "PBRMaterial";
  42818. };
  42819. /**
  42820. * Returns an array of the actively used textures.
  42821. * @returns - Array of BaseTextures
  42822. */
  42823. PBRMaterial.prototype.getActiveTextures = function () {
  42824. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42825. if (this._albedoTexture) {
  42826. activeTextures.push(this._albedoTexture);
  42827. }
  42828. if (this._ambientTexture) {
  42829. activeTextures.push(this._ambientTexture);
  42830. }
  42831. if (this._opacityTexture) {
  42832. activeTextures.push(this._opacityTexture);
  42833. }
  42834. if (this._reflectionTexture) {
  42835. activeTextures.push(this._reflectionTexture);
  42836. }
  42837. if (this._emissiveTexture) {
  42838. activeTextures.push(this._emissiveTexture);
  42839. }
  42840. if (this._reflectivityTexture) {
  42841. activeTextures.push(this._reflectivityTexture);
  42842. }
  42843. if (this._metallicTexture) {
  42844. activeTextures.push(this._metallicTexture);
  42845. }
  42846. if (this._microSurfaceTexture) {
  42847. activeTextures.push(this._microSurfaceTexture);
  42848. }
  42849. if (this._bumpTexture) {
  42850. activeTextures.push(this._bumpTexture);
  42851. }
  42852. if (this._lightmapTexture) {
  42853. activeTextures.push(this._lightmapTexture);
  42854. }
  42855. if (this._refractionTexture) {
  42856. activeTextures.push(this._refractionTexture);
  42857. }
  42858. return activeTextures;
  42859. };
  42860. /**
  42861. * Checks to see if a texture is used in the material.
  42862. * @param texture - Base texture to use.
  42863. * @returns - Boolean specifying if a texture is used in the material.
  42864. */
  42865. PBRMaterial.prototype.hasTexture = function (texture) {
  42866. if (_super.prototype.hasTexture.call(this, texture)) {
  42867. return true;
  42868. }
  42869. if (this._albedoTexture === texture) {
  42870. return true;
  42871. }
  42872. if (this._ambientTexture === texture) {
  42873. return true;
  42874. }
  42875. if (this._opacityTexture === texture) {
  42876. return true;
  42877. }
  42878. if (this._reflectionTexture === texture) {
  42879. return true;
  42880. }
  42881. if (this._reflectivityTexture === texture) {
  42882. return true;
  42883. }
  42884. if (this._metallicTexture === texture) {
  42885. return true;
  42886. }
  42887. if (this._microSurfaceTexture === texture) {
  42888. return true;
  42889. }
  42890. if (this._bumpTexture === texture) {
  42891. return true;
  42892. }
  42893. if (this._lightmapTexture === texture) {
  42894. return true;
  42895. }
  42896. if (this._refractionTexture === texture) {
  42897. return true;
  42898. }
  42899. return false;
  42900. };
  42901. /**
  42902. * Makes a duplicate of the current material.
  42903. * @param name - name to use for the new material.
  42904. */
  42905. PBRMaterial.prototype.clone = function (name) {
  42906. var _this = this;
  42907. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42908. clone.id = name;
  42909. clone.name = name;
  42910. return clone;
  42911. };
  42912. /**
  42913. * Serializes this PBR Material.
  42914. * @returns - An object with the serialized material.
  42915. */
  42916. PBRMaterial.prototype.serialize = function () {
  42917. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42918. serializationObject.customType = "BABYLON.PBRMaterial";
  42919. return serializationObject;
  42920. };
  42921. // Statics
  42922. /**
  42923. * Parses a PBR Material from a serialized object.
  42924. * @param source - Serialized object.
  42925. * @param scene - BJS scene instance.
  42926. * @param rootUrl - url for the scene object
  42927. * @returns - PBRMaterial
  42928. */
  42929. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42930. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42931. };
  42932. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42933. /**
  42934. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42935. */
  42936. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  42937. /**
  42938. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42939. */
  42940. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  42941. /**
  42942. * 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.
  42943. * They are also discarded below the alpha cutoff threshold to improve performances.
  42944. */
  42945. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  42946. __decorate([
  42947. BABYLON.serialize(),
  42948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42949. ], PBRMaterial.prototype, "directIntensity", void 0);
  42950. __decorate([
  42951. BABYLON.serialize(),
  42952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42953. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  42954. __decorate([
  42955. BABYLON.serialize(),
  42956. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42957. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  42958. __decorate([
  42959. BABYLON.serialize(),
  42960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42961. ], PBRMaterial.prototype, "specularIntensity", void 0);
  42962. __decorate([
  42963. BABYLON.serialize(),
  42964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42965. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  42966. __decorate([
  42967. BABYLON.serializeAsTexture(),
  42968. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42969. ], PBRMaterial.prototype, "albedoTexture", void 0);
  42970. __decorate([
  42971. BABYLON.serializeAsTexture(),
  42972. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42973. ], PBRMaterial.prototype, "ambientTexture", void 0);
  42974. __decorate([
  42975. BABYLON.serialize(),
  42976. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42977. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  42978. __decorate([
  42979. BABYLON.serializeAsTexture(),
  42980. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42981. ], PBRMaterial.prototype, "opacityTexture", void 0);
  42982. __decorate([
  42983. BABYLON.serializeAsTexture(),
  42984. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42985. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  42986. __decorate([
  42987. BABYLON.serializeAsTexture(),
  42988. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42989. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  42990. __decorate([
  42991. BABYLON.serializeAsTexture(),
  42992. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42993. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  42994. __decorate([
  42995. BABYLON.serializeAsTexture(),
  42996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42997. ], PBRMaterial.prototype, "metallicTexture", void 0);
  42998. __decorate([
  42999. BABYLON.serialize(),
  43000. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43001. ], PBRMaterial.prototype, "metallic", void 0);
  43002. __decorate([
  43003. BABYLON.serialize(),
  43004. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43005. ], PBRMaterial.prototype, "roughness", void 0);
  43006. __decorate([
  43007. BABYLON.serializeAsTexture(),
  43008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43009. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  43010. __decorate([
  43011. BABYLON.serializeAsTexture(),
  43012. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43013. ], PBRMaterial.prototype, "bumpTexture", void 0);
  43014. __decorate([
  43015. BABYLON.serializeAsTexture(),
  43016. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  43017. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  43018. __decorate([
  43019. BABYLON.serializeAsTexture(),
  43020. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43021. ], PBRMaterial.prototype, "refractionTexture", void 0);
  43022. __decorate([
  43023. BABYLON.serializeAsColor3("ambient"),
  43024. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43025. ], PBRMaterial.prototype, "ambientColor", void 0);
  43026. __decorate([
  43027. BABYLON.serializeAsColor3("albedo"),
  43028. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43029. ], PBRMaterial.prototype, "albedoColor", void 0);
  43030. __decorate([
  43031. BABYLON.serializeAsColor3("reflectivity"),
  43032. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43033. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  43034. __decorate([
  43035. BABYLON.serializeAsColor3("reflection"),
  43036. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43037. ], PBRMaterial.prototype, "reflectionColor", void 0);
  43038. __decorate([
  43039. BABYLON.serializeAsColor3("emissive"),
  43040. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43041. ], PBRMaterial.prototype, "emissiveColor", void 0);
  43042. __decorate([
  43043. BABYLON.serialize(),
  43044. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43045. ], PBRMaterial.prototype, "microSurface", void 0);
  43046. __decorate([
  43047. BABYLON.serialize(),
  43048. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43049. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  43050. __decorate([
  43051. BABYLON.serialize(),
  43052. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43053. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  43054. __decorate([
  43055. BABYLON.serialize(),
  43056. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43057. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  43058. __decorate([
  43059. BABYLON.serialize(),
  43060. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43061. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43062. __decorate([
  43063. BABYLON.serialize(),
  43064. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43065. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  43066. __decorate([
  43067. BABYLON.serialize(),
  43068. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43069. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  43070. __decorate([
  43071. BABYLON.serialize(),
  43072. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43073. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  43074. __decorate([
  43075. BABYLON.serialize(),
  43076. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43077. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  43078. __decorate([
  43079. BABYLON.serialize(),
  43080. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43081. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  43082. __decorate([
  43083. BABYLON.serialize(),
  43084. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43085. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  43086. __decorate([
  43087. BABYLON.serialize(),
  43088. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43089. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  43090. __decorate([
  43091. BABYLON.serialize(),
  43092. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43093. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  43094. __decorate([
  43095. BABYLON.serialize(),
  43096. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43097. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  43098. __decorate([
  43099. BABYLON.serialize(),
  43100. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43101. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  43102. __decorate([
  43103. BABYLON.serialize(),
  43104. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43105. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  43106. __decorate([
  43107. BABYLON.serialize(),
  43108. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43109. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  43110. __decorate([
  43111. BABYLON.serialize(),
  43112. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43113. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  43114. __decorate([
  43115. BABYLON.serialize(),
  43116. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43117. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43118. __decorate([
  43119. BABYLON.serialize(),
  43120. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43121. ], PBRMaterial.prototype, "useParallax", void 0);
  43122. __decorate([
  43123. BABYLON.serialize(),
  43124. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43125. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  43126. __decorate([
  43127. BABYLON.serialize(),
  43128. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43129. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  43130. __decorate([
  43131. BABYLON.serialize(),
  43132. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43133. ], PBRMaterial.prototype, "disableLighting", void 0);
  43134. __decorate([
  43135. BABYLON.serialize(),
  43136. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43137. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  43138. __decorate([
  43139. BABYLON.serialize(),
  43140. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43141. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  43142. __decorate([
  43143. BABYLON.serialize(),
  43144. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43145. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  43146. __decorate([
  43147. BABYLON.serialize(),
  43148. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43149. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  43150. __decorate([
  43151. BABYLON.serialize(),
  43152. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43153. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  43154. __decorate([
  43155. BABYLON.serialize(),
  43156. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43157. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  43158. __decorate([
  43159. BABYLON.serialize(),
  43160. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43161. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  43162. __decorate([
  43163. BABYLON.serializeAsTexture(),
  43164. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43165. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  43166. __decorate([
  43167. BABYLON.serialize(),
  43168. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43169. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  43170. __decorate([
  43171. BABYLON.serialize(),
  43172. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43173. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  43174. __decorate([
  43175. BABYLON.serialize(),
  43176. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43177. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  43178. __decorate([
  43179. BABYLON.serialize(),
  43180. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43181. ], PBRMaterial.prototype, "unlit", void 0);
  43182. return PBRMaterial;
  43183. }(BABYLON.PBRBaseMaterial));
  43184. BABYLON.PBRMaterial = PBRMaterial;
  43185. })(BABYLON || (BABYLON = {}));
  43186. //# sourceMappingURL=babylon.pbrMaterial.js.map
  43187. "use strict";
  43188. var BABYLON;
  43189. (function (BABYLON) {
  43190. /**
  43191. * The PBR material of BJS following the metal roughness convention.
  43192. *
  43193. * This fits to the PBR convention in the GLTF definition:
  43194. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  43195. */
  43196. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  43197. __extends(PBRMetallicRoughnessMaterial, _super);
  43198. /**
  43199. * Instantiates a new PBRMetalRoughnessMaterial instance.
  43200. *
  43201. * @param name The material name
  43202. * @param scene The scene the material will be use in.
  43203. */
  43204. function PBRMetallicRoughnessMaterial(name, scene) {
  43205. var _this = _super.call(this, name, scene) || this;
  43206. _this._useRoughnessFromMetallicTextureAlpha = false;
  43207. _this._useRoughnessFromMetallicTextureGreen = true;
  43208. _this._useMetallnessFromMetallicTextureBlue = true;
  43209. _this.metallic = 1.0;
  43210. _this.roughness = 1.0;
  43211. return _this;
  43212. }
  43213. /**
  43214. * Return the currrent class name of the material.
  43215. */
  43216. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  43217. return "PBRMetallicRoughnessMaterial";
  43218. };
  43219. /**
  43220. * Return the active textures of the material.
  43221. */
  43222. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  43223. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43224. if (this.baseTexture) {
  43225. activeTextures.push(this.baseTexture);
  43226. }
  43227. if (this.metallicRoughnessTexture) {
  43228. activeTextures.push(this.metallicRoughnessTexture);
  43229. }
  43230. return activeTextures;
  43231. };
  43232. /**
  43233. * Checks to see if a texture is used in the material.
  43234. * @param texture - Base texture to use.
  43235. * @returns - Boolean specifying if a texture is used in the material.
  43236. */
  43237. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  43238. if (_super.prototype.hasTexture.call(this, texture)) {
  43239. return true;
  43240. }
  43241. if (this.baseTexture === texture) {
  43242. return true;
  43243. }
  43244. if (this.metallicRoughnessTexture === texture) {
  43245. return true;
  43246. }
  43247. return false;
  43248. };
  43249. /**
  43250. * Makes a duplicate of the current material.
  43251. * @param name - name to use for the new material.
  43252. */
  43253. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  43254. var _this = this;
  43255. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  43256. clone.id = name;
  43257. clone.name = name;
  43258. return clone;
  43259. };
  43260. /**
  43261. * Serialize the material to a parsable JSON object.
  43262. */
  43263. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  43264. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43265. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  43266. return serializationObject;
  43267. };
  43268. /**
  43269. * Parses a JSON object correponding to the serialize function.
  43270. */
  43271. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  43272. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  43273. };
  43274. __decorate([
  43275. BABYLON.serializeAsColor3(),
  43276. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43277. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  43278. __decorate([
  43279. BABYLON.serializeAsTexture(),
  43280. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43281. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  43282. __decorate([
  43283. BABYLON.serialize(),
  43284. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43285. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  43286. __decorate([
  43287. BABYLON.serialize(),
  43288. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43289. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  43290. __decorate([
  43291. BABYLON.serializeAsTexture(),
  43292. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  43293. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  43294. return PBRMetallicRoughnessMaterial;
  43295. }(BABYLON.PBRBaseSimpleMaterial));
  43296. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  43297. })(BABYLON || (BABYLON = {}));
  43298. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  43299. "use strict";
  43300. var BABYLON;
  43301. (function (BABYLON) {
  43302. /**
  43303. * The PBR material of BJS following the specular glossiness convention.
  43304. *
  43305. * This fits to the PBR convention in the GLTF definition:
  43306. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  43307. */
  43308. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  43309. __extends(PBRSpecularGlossinessMaterial, _super);
  43310. /**
  43311. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  43312. *
  43313. * @param name The material name
  43314. * @param scene The scene the material will be use in.
  43315. */
  43316. function PBRSpecularGlossinessMaterial(name, scene) {
  43317. var _this = _super.call(this, name, scene) || this;
  43318. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  43319. return _this;
  43320. }
  43321. /**
  43322. * Return the currrent class name of the material.
  43323. */
  43324. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  43325. return "PBRSpecularGlossinessMaterial";
  43326. };
  43327. /**
  43328. * Return the active textures of the material.
  43329. */
  43330. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  43331. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43332. if (this.diffuseTexture) {
  43333. activeTextures.push(this.diffuseTexture);
  43334. }
  43335. if (this.specularGlossinessTexture) {
  43336. activeTextures.push(this.specularGlossinessTexture);
  43337. }
  43338. return activeTextures;
  43339. };
  43340. /**
  43341. * Checks to see if a texture is used in the material.
  43342. * @param texture - Base texture to use.
  43343. * @returns - Boolean specifying if a texture is used in the material.
  43344. */
  43345. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  43346. if (_super.prototype.hasTexture.call(this, texture)) {
  43347. return true;
  43348. }
  43349. if (this.diffuseTexture === texture) {
  43350. return true;
  43351. }
  43352. if (this.specularGlossinessTexture === texture) {
  43353. return true;
  43354. }
  43355. return false;
  43356. };
  43357. /**
  43358. * Makes a duplicate of the current material.
  43359. * @param name - name to use for the new material.
  43360. */
  43361. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  43362. var _this = this;
  43363. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  43364. clone.id = name;
  43365. clone.name = name;
  43366. return clone;
  43367. };
  43368. /**
  43369. * Serialize the material to a parsable JSON object.
  43370. */
  43371. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  43372. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43373. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  43374. return serializationObject;
  43375. };
  43376. /**
  43377. * Parses a JSON object correponding to the serialize function.
  43378. */
  43379. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  43380. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  43381. };
  43382. __decorate([
  43383. BABYLON.serializeAsColor3("diffuse"),
  43384. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43385. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  43386. __decorate([
  43387. BABYLON.serializeAsTexture(),
  43388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43389. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  43390. __decorate([
  43391. BABYLON.serializeAsColor3("specular"),
  43392. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  43393. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  43394. __decorate([
  43395. BABYLON.serialize(),
  43396. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  43397. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  43398. __decorate([
  43399. BABYLON.serializeAsTexture(),
  43400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  43401. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  43402. return PBRSpecularGlossinessMaterial;
  43403. }(BABYLON.PBRBaseSimpleMaterial));
  43404. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  43405. })(BABYLON || (BABYLON = {}));
  43406. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  43407. "use strict";
  43408. var BABYLON;
  43409. (function (BABYLON) {
  43410. BABYLON.CameraInputTypes = {};
  43411. var CameraInputsManager = /** @class */ (function () {
  43412. function CameraInputsManager(camera) {
  43413. this.attached = {};
  43414. this.camera = camera;
  43415. this.checkInputs = function () { };
  43416. }
  43417. /**
  43418. * Add an input method to a camera.
  43419. * builtin inputs example: camera.inputs.addGamepad();
  43420. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  43421. * @param input camera input method
  43422. */
  43423. CameraInputsManager.prototype.add = function (input) {
  43424. var type = input.getSimpleName();
  43425. if (this.attached[type]) {
  43426. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  43427. return;
  43428. }
  43429. this.attached[type] = input;
  43430. input.camera = this.camera;
  43431. //for checkInputs, we are dynamically creating a function
  43432. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  43433. if (input.checkInputs) {
  43434. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43435. }
  43436. if (this.attachedElement) {
  43437. input.attachControl(this.attachedElement);
  43438. }
  43439. };
  43440. /**
  43441. * Remove a specific input method from a camera
  43442. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  43443. * @param inputToRemove camera input method
  43444. */
  43445. CameraInputsManager.prototype.remove = function (inputToRemove) {
  43446. for (var cam in this.attached) {
  43447. var input = this.attached[cam];
  43448. if (input === inputToRemove) {
  43449. input.detachControl(this.attachedElement);
  43450. input.camera = null;
  43451. delete this.attached[cam];
  43452. this.rebuildInputCheck();
  43453. }
  43454. }
  43455. };
  43456. CameraInputsManager.prototype.removeByType = function (inputType) {
  43457. for (var cam in this.attached) {
  43458. var input = this.attached[cam];
  43459. if (input.getClassName() === inputType) {
  43460. input.detachControl(this.attachedElement);
  43461. input.camera = null;
  43462. delete this.attached[cam];
  43463. this.rebuildInputCheck();
  43464. }
  43465. }
  43466. };
  43467. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  43468. var current = this.checkInputs;
  43469. return function () {
  43470. current();
  43471. fn();
  43472. };
  43473. };
  43474. CameraInputsManager.prototype.attachInput = function (input) {
  43475. if (this.attachedElement) {
  43476. input.attachControl(this.attachedElement, this.noPreventDefault);
  43477. }
  43478. };
  43479. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  43480. if (noPreventDefault === void 0) { noPreventDefault = false; }
  43481. if (this.attachedElement) {
  43482. return;
  43483. }
  43484. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  43485. this.attachedElement = element;
  43486. this.noPreventDefault = noPreventDefault;
  43487. for (var cam in this.attached) {
  43488. this.attached[cam].attachControl(element, noPreventDefault);
  43489. }
  43490. };
  43491. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  43492. if (disconnect === void 0) { disconnect = false; }
  43493. if (this.attachedElement !== element) {
  43494. return;
  43495. }
  43496. for (var cam in this.attached) {
  43497. this.attached[cam].detachControl(element);
  43498. if (disconnect) {
  43499. this.attached[cam].camera = null;
  43500. }
  43501. }
  43502. this.attachedElement = null;
  43503. };
  43504. CameraInputsManager.prototype.rebuildInputCheck = function () {
  43505. this.checkInputs = function () { };
  43506. for (var cam in this.attached) {
  43507. var input = this.attached[cam];
  43508. if (input.checkInputs) {
  43509. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43510. }
  43511. }
  43512. };
  43513. /**
  43514. * Remove all attached input methods from a camera
  43515. */
  43516. CameraInputsManager.prototype.clear = function () {
  43517. if (this.attachedElement) {
  43518. this.detachElement(this.attachedElement, true);
  43519. }
  43520. this.attached = {};
  43521. this.attachedElement = null;
  43522. this.checkInputs = function () { };
  43523. };
  43524. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  43525. var inputs = {};
  43526. for (var cam in this.attached) {
  43527. var input = this.attached[cam];
  43528. var res = BABYLON.SerializationHelper.Serialize(input);
  43529. inputs[input.getClassName()] = res;
  43530. }
  43531. serializedCamera.inputsmgr = inputs;
  43532. };
  43533. CameraInputsManager.prototype.parse = function (parsedCamera) {
  43534. var parsedInputs = parsedCamera.inputsmgr;
  43535. if (parsedInputs) {
  43536. this.clear();
  43537. for (var n in parsedInputs) {
  43538. var construct = BABYLON.CameraInputTypes[n];
  43539. if (construct) {
  43540. var parsedinput = parsedInputs[n];
  43541. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  43542. this.add(input);
  43543. }
  43544. }
  43545. }
  43546. else {
  43547. //2016-03-08 this part is for managing backward compatibility
  43548. for (var n in this.attached) {
  43549. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  43550. if (construct) {
  43551. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  43552. this.remove(this.attached[n]);
  43553. this.add(input);
  43554. }
  43555. }
  43556. }
  43557. };
  43558. return CameraInputsManager;
  43559. }());
  43560. BABYLON.CameraInputsManager = CameraInputsManager;
  43561. })(BABYLON || (BABYLON = {}));
  43562. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  43563. "use strict";
  43564. var BABYLON;
  43565. (function (BABYLON) {
  43566. var TargetCamera = /** @class */ (function (_super) {
  43567. __extends(TargetCamera, _super);
  43568. function TargetCamera(name, position, scene) {
  43569. var _this = _super.call(this, name, position, scene) || this;
  43570. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43571. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  43572. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  43573. _this.speed = 2.0;
  43574. _this.noRotationConstraint = false;
  43575. _this.lockedTarget = null;
  43576. _this._currentTarget = BABYLON.Vector3.Zero();
  43577. _this._viewMatrix = BABYLON.Matrix.Zero();
  43578. _this._camMatrix = BABYLON.Matrix.Zero();
  43579. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  43580. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  43581. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  43582. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  43583. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  43584. _this._lookAtTemp = BABYLON.Matrix.Zero();
  43585. _this._tempMatrix = BABYLON.Matrix.Zero();
  43586. return _this;
  43587. }
  43588. TargetCamera.prototype.getFrontPosition = function (distance) {
  43589. this.getWorldMatrix();
  43590. var direction = this.getTarget().subtract(this.position);
  43591. direction.normalize();
  43592. direction.scaleInPlace(distance);
  43593. return this.globalPosition.add(direction);
  43594. };
  43595. TargetCamera.prototype._getLockedTargetPosition = function () {
  43596. if (!this.lockedTarget) {
  43597. return null;
  43598. }
  43599. if (this.lockedTarget.absolutePosition) {
  43600. this.lockedTarget.computeWorldMatrix();
  43601. }
  43602. return this.lockedTarget.absolutePosition || this.lockedTarget;
  43603. };
  43604. TargetCamera.prototype.storeState = function () {
  43605. this._storedPosition = this.position.clone();
  43606. this._storedRotation = this.rotation.clone();
  43607. if (this.rotationQuaternion) {
  43608. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  43609. }
  43610. return _super.prototype.storeState.call(this);
  43611. };
  43612. /**
  43613. * Restored camera state. You must call storeState() first
  43614. */
  43615. TargetCamera.prototype._restoreStateValues = function () {
  43616. if (!_super.prototype._restoreStateValues.call(this)) {
  43617. return false;
  43618. }
  43619. this.position = this._storedPosition.clone();
  43620. this.rotation = this._storedRotation.clone();
  43621. if (this.rotationQuaternion) {
  43622. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  43623. }
  43624. this.cameraDirection.copyFromFloats(0, 0, 0);
  43625. this.cameraRotation.copyFromFloats(0, 0);
  43626. return true;
  43627. };
  43628. // Cache
  43629. TargetCamera.prototype._initCache = function () {
  43630. _super.prototype._initCache.call(this);
  43631. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43632. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43633. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43634. };
  43635. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43636. if (!ignoreParentClass) {
  43637. _super.prototype._updateCache.call(this);
  43638. }
  43639. var lockedTargetPosition = this._getLockedTargetPosition();
  43640. if (!lockedTargetPosition) {
  43641. this._cache.lockedTarget = null;
  43642. }
  43643. else {
  43644. if (!this._cache.lockedTarget) {
  43645. this._cache.lockedTarget = lockedTargetPosition.clone();
  43646. }
  43647. else {
  43648. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43649. }
  43650. }
  43651. this._cache.rotation.copyFrom(this.rotation);
  43652. if (this.rotationQuaternion)
  43653. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43654. };
  43655. // Synchronized
  43656. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43657. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43658. return false;
  43659. }
  43660. var lockedTargetPosition = this._getLockedTargetPosition();
  43661. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43662. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43663. };
  43664. // Methods
  43665. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43666. var engine = this.getEngine();
  43667. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43668. };
  43669. // Target
  43670. TargetCamera.prototype.setTarget = function (target) {
  43671. this.upVector.normalize();
  43672. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43673. this._camMatrix.invert();
  43674. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43675. var vDir = target.subtract(this.position);
  43676. if (vDir.x >= 0.0) {
  43677. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43678. }
  43679. else {
  43680. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43681. }
  43682. this.rotation.z = 0;
  43683. if (isNaN(this.rotation.x)) {
  43684. this.rotation.x = 0;
  43685. }
  43686. if (isNaN(this.rotation.y)) {
  43687. this.rotation.y = 0;
  43688. }
  43689. if (isNaN(this.rotation.z)) {
  43690. this.rotation.z = 0;
  43691. }
  43692. if (this.rotationQuaternion) {
  43693. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43694. }
  43695. };
  43696. /**
  43697. * Return the current target position of the camera. This value is expressed in local space.
  43698. */
  43699. TargetCamera.prototype.getTarget = function () {
  43700. return this._currentTarget;
  43701. };
  43702. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43703. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43704. };
  43705. TargetCamera.prototype._updatePosition = function () {
  43706. if (this.parent) {
  43707. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43708. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43709. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43710. return;
  43711. }
  43712. this.position.addInPlace(this.cameraDirection);
  43713. };
  43714. TargetCamera.prototype._checkInputs = function () {
  43715. var needToMove = this._decideIfNeedsToMove();
  43716. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43717. // Move
  43718. if (needToMove) {
  43719. this._updatePosition();
  43720. }
  43721. // Rotate
  43722. if (needToRotate) {
  43723. this.rotation.x += this.cameraRotation.x;
  43724. this.rotation.y += this.cameraRotation.y;
  43725. //rotate, if quaternion is set and rotation was used
  43726. if (this.rotationQuaternion) {
  43727. var len = this.rotation.lengthSquared();
  43728. if (len) {
  43729. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43730. }
  43731. }
  43732. if (!this.noRotationConstraint) {
  43733. var limit = (Math.PI / 2) * 0.95;
  43734. if (this.rotation.x > limit)
  43735. this.rotation.x = limit;
  43736. if (this.rotation.x < -limit)
  43737. this.rotation.x = -limit;
  43738. }
  43739. }
  43740. // Inertia
  43741. if (needToMove) {
  43742. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43743. this.cameraDirection.x = 0;
  43744. }
  43745. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43746. this.cameraDirection.y = 0;
  43747. }
  43748. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43749. this.cameraDirection.z = 0;
  43750. }
  43751. this.cameraDirection.scaleInPlace(this.inertia);
  43752. }
  43753. if (needToRotate) {
  43754. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43755. this.cameraRotation.x = 0;
  43756. }
  43757. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43758. this.cameraRotation.y = 0;
  43759. }
  43760. this.cameraRotation.scaleInPlace(this.inertia);
  43761. }
  43762. _super.prototype._checkInputs.call(this);
  43763. };
  43764. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43765. if (this.rotationQuaternion) {
  43766. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43767. }
  43768. else {
  43769. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43770. }
  43771. //update the up vector!
  43772. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43773. };
  43774. TargetCamera.prototype._getViewMatrix = function () {
  43775. if (this.lockedTarget) {
  43776. this.setTarget(this._getLockedTargetPosition());
  43777. }
  43778. // Compute
  43779. this._updateCameraRotationMatrix();
  43780. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43781. // Computing target and final matrix
  43782. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43783. if (this.getScene().useRightHandedSystem) {
  43784. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43785. }
  43786. else {
  43787. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43788. }
  43789. return this._viewMatrix;
  43790. };
  43791. /**
  43792. * @override
  43793. * Override Camera.createRigCamera
  43794. */
  43795. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43796. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43797. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43798. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43799. if (!this.rotationQuaternion) {
  43800. this.rotationQuaternion = new BABYLON.Quaternion();
  43801. }
  43802. rigCamera._cameraRigParams = {};
  43803. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43804. }
  43805. return rigCamera;
  43806. }
  43807. return null;
  43808. };
  43809. /**
  43810. * @override
  43811. * Override Camera._updateRigCameras
  43812. */
  43813. TargetCamera.prototype._updateRigCameras = function () {
  43814. var camLeft = this._rigCameras[0];
  43815. var camRight = this._rigCameras[1];
  43816. switch (this.cameraRigMode) {
  43817. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43818. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43819. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43820. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43821. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43822. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43823. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43824. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43825. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43826. camLeft.setTarget(this.getTarget());
  43827. camRight.setTarget(this.getTarget());
  43828. break;
  43829. case BABYLON.Camera.RIG_MODE_VR:
  43830. if (camLeft.rotationQuaternion) {
  43831. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43832. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43833. }
  43834. else {
  43835. camLeft.rotation.copyFrom(this.rotation);
  43836. camRight.rotation.copyFrom(this.rotation);
  43837. }
  43838. camLeft.position.copyFrom(this.position);
  43839. camRight.position.copyFrom(this.position);
  43840. break;
  43841. }
  43842. _super.prototype._updateRigCameras.call(this);
  43843. };
  43844. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43845. if (!this._rigCamTransformMatrix) {
  43846. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43847. }
  43848. var target = this.getTarget();
  43849. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43850. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43851. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43852. };
  43853. TargetCamera.prototype.getClassName = function () {
  43854. return "TargetCamera";
  43855. };
  43856. __decorate([
  43857. BABYLON.serializeAsVector3()
  43858. ], TargetCamera.prototype, "rotation", void 0);
  43859. __decorate([
  43860. BABYLON.serialize()
  43861. ], TargetCamera.prototype, "speed", void 0);
  43862. __decorate([
  43863. BABYLON.serializeAsMeshReference("lockedTargetId")
  43864. ], TargetCamera.prototype, "lockedTarget", void 0);
  43865. return TargetCamera;
  43866. }(BABYLON.Camera));
  43867. BABYLON.TargetCamera = TargetCamera;
  43868. })(BABYLON || (BABYLON = {}));
  43869. //# sourceMappingURL=babylon.targetCamera.js.map
  43870. "use strict";
  43871. var BABYLON;
  43872. (function (BABYLON) {
  43873. var FreeCameraMouseInput = /** @class */ (function () {
  43874. function FreeCameraMouseInput(touchEnabled) {
  43875. if (touchEnabled === void 0) { touchEnabled = true; }
  43876. this.touchEnabled = touchEnabled;
  43877. this.buttons = [0, 1, 2];
  43878. this.angularSensibility = 2000.0;
  43879. this.previousPosition = null;
  43880. }
  43881. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43882. var _this = this;
  43883. var engine = this.camera.getEngine();
  43884. if (!this._pointerInput) {
  43885. this._pointerInput = function (p, s) {
  43886. var evt = p.event;
  43887. if (engine.isInVRExclusivePointerMode) {
  43888. return;
  43889. }
  43890. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43891. return;
  43892. }
  43893. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43894. return;
  43895. }
  43896. var srcElement = (evt.srcElement || evt.target);
  43897. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43898. try {
  43899. srcElement.setPointerCapture(evt.pointerId);
  43900. }
  43901. catch (e) {
  43902. //Nothing to do with the error. Execution will continue.
  43903. }
  43904. _this.previousPosition = {
  43905. x: evt.clientX,
  43906. y: evt.clientY
  43907. };
  43908. if (!noPreventDefault) {
  43909. evt.preventDefault();
  43910. element.focus();
  43911. }
  43912. }
  43913. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43914. try {
  43915. srcElement.releasePointerCapture(evt.pointerId);
  43916. }
  43917. catch (e) {
  43918. //Nothing to do with the error.
  43919. }
  43920. _this.previousPosition = null;
  43921. if (!noPreventDefault) {
  43922. evt.preventDefault();
  43923. }
  43924. }
  43925. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43926. if (!_this.previousPosition || engine.isPointerLock) {
  43927. return;
  43928. }
  43929. var offsetX = evt.clientX - _this.previousPosition.x;
  43930. var offsetY = evt.clientY - _this.previousPosition.y;
  43931. if (_this.camera.getScene().useRightHandedSystem) {
  43932. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43933. }
  43934. else {
  43935. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43936. }
  43937. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43938. _this.previousPosition = {
  43939. x: evt.clientX,
  43940. y: evt.clientY
  43941. };
  43942. if (!noPreventDefault) {
  43943. evt.preventDefault();
  43944. }
  43945. }
  43946. };
  43947. }
  43948. this._onMouseMove = function (evt) {
  43949. if (!engine.isPointerLock) {
  43950. return;
  43951. }
  43952. if (engine.isInVRExclusivePointerMode) {
  43953. return;
  43954. }
  43955. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43956. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43957. if (_this.camera.getScene().useRightHandedSystem) {
  43958. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43959. }
  43960. else {
  43961. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43962. }
  43963. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43964. _this.previousPosition = null;
  43965. if (!noPreventDefault) {
  43966. evt.preventDefault();
  43967. }
  43968. };
  43969. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  43970. element.addEventListener("mousemove", this._onMouseMove, false);
  43971. };
  43972. FreeCameraMouseInput.prototype.detachControl = function (element) {
  43973. if (this._observer && element) {
  43974. this.camera.getScene().onPointerObservable.remove(this._observer);
  43975. if (this._onMouseMove) {
  43976. element.removeEventListener("mousemove", this._onMouseMove);
  43977. }
  43978. this._observer = null;
  43979. this._onMouseMove = null;
  43980. this.previousPosition = null;
  43981. }
  43982. };
  43983. FreeCameraMouseInput.prototype.getClassName = function () {
  43984. return "FreeCameraMouseInput";
  43985. };
  43986. FreeCameraMouseInput.prototype.getSimpleName = function () {
  43987. return "mouse";
  43988. };
  43989. __decorate([
  43990. BABYLON.serialize()
  43991. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  43992. __decorate([
  43993. BABYLON.serialize()
  43994. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  43995. return FreeCameraMouseInput;
  43996. }());
  43997. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  43998. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  43999. })(BABYLON || (BABYLON = {}));
  44000. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  44001. "use strict";
  44002. var BABYLON;
  44003. (function (BABYLON) {
  44004. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  44005. function FreeCameraKeyboardMoveInput() {
  44006. this._keys = new Array();
  44007. this.keysUp = [38];
  44008. this.keysDown = [40];
  44009. this.keysLeft = [37];
  44010. this.keysRight = [39];
  44011. }
  44012. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44013. var _this = this;
  44014. if (this._onCanvasBlurObserver) {
  44015. return;
  44016. }
  44017. this._scene = this.camera.getScene();
  44018. this._engine = this._scene.getEngine();
  44019. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44020. _this._keys = [];
  44021. });
  44022. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44023. var evt = info.event;
  44024. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44025. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44026. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44027. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44028. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  44029. var index = _this._keys.indexOf(evt.keyCode);
  44030. if (index === -1) {
  44031. _this._keys.push(evt.keyCode);
  44032. }
  44033. if (!noPreventDefault) {
  44034. evt.preventDefault();
  44035. }
  44036. }
  44037. }
  44038. else {
  44039. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44040. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44041. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44042. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  44043. var index = _this._keys.indexOf(evt.keyCode);
  44044. if (index >= 0) {
  44045. _this._keys.splice(index, 1);
  44046. }
  44047. if (!noPreventDefault) {
  44048. evt.preventDefault();
  44049. }
  44050. }
  44051. }
  44052. });
  44053. };
  44054. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44055. if (this._scene) {
  44056. if (this._onKeyboardObserver) {
  44057. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44058. }
  44059. if (this._onCanvasBlurObserver) {
  44060. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44061. }
  44062. this._onKeyboardObserver = null;
  44063. this._onCanvasBlurObserver = null;
  44064. }
  44065. this._keys = [];
  44066. };
  44067. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44068. if (this._onKeyboardObserver) {
  44069. var camera = this.camera;
  44070. // Keyboard
  44071. for (var index = 0; index < this._keys.length; index++) {
  44072. var keyCode = this._keys[index];
  44073. var speed = camera._computeLocalCameraSpeed();
  44074. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44075. camera._localDirection.copyFromFloats(-speed, 0, 0);
  44076. }
  44077. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44078. camera._localDirection.copyFromFloats(0, 0, speed);
  44079. }
  44080. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44081. camera._localDirection.copyFromFloats(speed, 0, 0);
  44082. }
  44083. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44084. camera._localDirection.copyFromFloats(0, 0, -speed);
  44085. }
  44086. if (camera.getScene().useRightHandedSystem) {
  44087. camera._localDirection.z *= -1;
  44088. }
  44089. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  44090. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  44091. camera.cameraDirection.addInPlace(camera._transformedDirection);
  44092. }
  44093. }
  44094. };
  44095. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  44096. return "FreeCameraKeyboardMoveInput";
  44097. };
  44098. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  44099. this._keys = [];
  44100. };
  44101. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44102. return "keyboard";
  44103. };
  44104. __decorate([
  44105. BABYLON.serialize()
  44106. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44107. __decorate([
  44108. BABYLON.serialize()
  44109. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44110. __decorate([
  44111. BABYLON.serialize()
  44112. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44113. __decorate([
  44114. BABYLON.serialize()
  44115. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44116. return FreeCameraKeyboardMoveInput;
  44117. }());
  44118. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  44119. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  44120. })(BABYLON || (BABYLON = {}));
  44121. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  44122. "use strict";
  44123. var BABYLON;
  44124. (function (BABYLON) {
  44125. var FreeCameraInputsManager = /** @class */ (function (_super) {
  44126. __extends(FreeCameraInputsManager, _super);
  44127. function FreeCameraInputsManager(camera) {
  44128. return _super.call(this, camera) || this;
  44129. }
  44130. FreeCameraInputsManager.prototype.addKeyboard = function () {
  44131. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  44132. return this;
  44133. };
  44134. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  44135. if (touchEnabled === void 0) { touchEnabled = true; }
  44136. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  44137. return this;
  44138. };
  44139. FreeCameraInputsManager.prototype.addGamepad = function () {
  44140. this.add(new BABYLON.FreeCameraGamepadInput());
  44141. return this;
  44142. };
  44143. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  44144. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  44145. return this;
  44146. };
  44147. FreeCameraInputsManager.prototype.addTouch = function () {
  44148. this.add(new BABYLON.FreeCameraTouchInput());
  44149. return this;
  44150. };
  44151. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  44152. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  44153. return this;
  44154. };
  44155. return FreeCameraInputsManager;
  44156. }(BABYLON.CameraInputsManager));
  44157. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  44158. })(BABYLON || (BABYLON = {}));
  44159. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  44160. "use strict";
  44161. var BABYLON;
  44162. (function (BABYLON) {
  44163. var FreeCamera = /** @class */ (function (_super) {
  44164. __extends(FreeCamera, _super);
  44165. function FreeCamera(name, position, scene) {
  44166. var _this = _super.call(this, name, position, scene) || this;
  44167. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  44168. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  44169. _this.checkCollisions = false;
  44170. _this.applyGravity = false;
  44171. _this._needMoveForGravity = false;
  44172. _this._oldPosition = BABYLON.Vector3.Zero();
  44173. _this._diffPosition = BABYLON.Vector3.Zero();
  44174. _this._newPosition = BABYLON.Vector3.Zero();
  44175. // Collisions
  44176. _this._collisionMask = -1;
  44177. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44178. if (collidedMesh === void 0) { collidedMesh = null; }
  44179. //TODO move this to the collision coordinator!
  44180. if (_this.getScene().workerCollisions)
  44181. newPosition.multiplyInPlace(_this._collider._radius);
  44182. var updatePosition = function (newPos) {
  44183. _this._newPosition.copyFrom(newPos);
  44184. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  44185. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  44186. _this.position.addInPlace(_this._diffPosition);
  44187. if (_this.onCollide && collidedMesh) {
  44188. _this.onCollide(collidedMesh);
  44189. }
  44190. }
  44191. };
  44192. updatePosition(newPosition);
  44193. };
  44194. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  44195. _this.inputs.addKeyboard().addMouse();
  44196. return _this;
  44197. }
  44198. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  44199. //-- begin properties for backward compatibility for inputs
  44200. /**
  44201. * Gets the input sensibility for a mouse input. (default is 2000.0)
  44202. * Higher values reduce sensitivity.
  44203. */
  44204. get: function () {
  44205. var mouse = this.inputs.attached["mouse"];
  44206. if (mouse)
  44207. return mouse.angularSensibility;
  44208. return 0;
  44209. },
  44210. /**
  44211. * Sets the input sensibility for a mouse input. (default is 2000.0)
  44212. * Higher values reduce sensitivity.
  44213. */
  44214. set: function (value) {
  44215. var mouse = this.inputs.attached["mouse"];
  44216. if (mouse)
  44217. mouse.angularSensibility = value;
  44218. },
  44219. enumerable: true,
  44220. configurable: true
  44221. });
  44222. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  44223. get: function () {
  44224. var keyboard = this.inputs.attached["keyboard"];
  44225. if (keyboard)
  44226. return keyboard.keysUp;
  44227. return [];
  44228. },
  44229. set: function (value) {
  44230. var keyboard = this.inputs.attached["keyboard"];
  44231. if (keyboard)
  44232. keyboard.keysUp = value;
  44233. },
  44234. enumerable: true,
  44235. configurable: true
  44236. });
  44237. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  44238. get: function () {
  44239. var keyboard = this.inputs.attached["keyboard"];
  44240. if (keyboard)
  44241. return keyboard.keysDown;
  44242. return [];
  44243. },
  44244. set: function (value) {
  44245. var keyboard = this.inputs.attached["keyboard"];
  44246. if (keyboard)
  44247. keyboard.keysDown = value;
  44248. },
  44249. enumerable: true,
  44250. configurable: true
  44251. });
  44252. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  44253. get: function () {
  44254. var keyboard = this.inputs.attached["keyboard"];
  44255. if (keyboard)
  44256. return keyboard.keysLeft;
  44257. return [];
  44258. },
  44259. set: function (value) {
  44260. var keyboard = this.inputs.attached["keyboard"];
  44261. if (keyboard)
  44262. keyboard.keysLeft = value;
  44263. },
  44264. enumerable: true,
  44265. configurable: true
  44266. });
  44267. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  44268. get: function () {
  44269. var keyboard = this.inputs.attached["keyboard"];
  44270. if (keyboard)
  44271. return keyboard.keysRight;
  44272. return [];
  44273. },
  44274. set: function (value) {
  44275. var keyboard = this.inputs.attached["keyboard"];
  44276. if (keyboard)
  44277. keyboard.keysRight = value;
  44278. },
  44279. enumerable: true,
  44280. configurable: true
  44281. });
  44282. // Controls
  44283. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  44284. this.inputs.attachElement(element, noPreventDefault);
  44285. };
  44286. FreeCamera.prototype.detachControl = function (element) {
  44287. this.inputs.detachElement(element);
  44288. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  44289. this.cameraRotation = new BABYLON.Vector2(0, 0);
  44290. };
  44291. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  44292. get: function () {
  44293. return this._collisionMask;
  44294. },
  44295. set: function (mask) {
  44296. this._collisionMask = !isNaN(mask) ? mask : -1;
  44297. },
  44298. enumerable: true,
  44299. configurable: true
  44300. });
  44301. FreeCamera.prototype._collideWithWorld = function (displacement) {
  44302. var globalPosition;
  44303. if (this.parent) {
  44304. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  44305. }
  44306. else {
  44307. globalPosition = this.position;
  44308. }
  44309. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  44310. this._oldPosition.addInPlace(this.ellipsoidOffset);
  44311. if (!this._collider) {
  44312. this._collider = new BABYLON.Collider();
  44313. }
  44314. this._collider._radius = this.ellipsoid;
  44315. this._collider.collisionMask = this._collisionMask;
  44316. //no need for clone, as long as gravity is not on.
  44317. var actualDisplacement = displacement;
  44318. //add gravity to the direction to prevent the dual-collision checking
  44319. if (this.applyGravity) {
  44320. //this prevents mending with cameraDirection, a global variable of the free camera class.
  44321. actualDisplacement = displacement.add(this.getScene().gravity);
  44322. }
  44323. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44324. };
  44325. FreeCamera.prototype._checkInputs = function () {
  44326. if (!this._localDirection) {
  44327. this._localDirection = BABYLON.Vector3.Zero();
  44328. this._transformedDirection = BABYLON.Vector3.Zero();
  44329. }
  44330. this.inputs.checkInputs();
  44331. _super.prototype._checkInputs.call(this);
  44332. };
  44333. FreeCamera.prototype._decideIfNeedsToMove = function () {
  44334. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  44335. };
  44336. FreeCamera.prototype._updatePosition = function () {
  44337. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  44338. this._collideWithWorld(this.cameraDirection);
  44339. }
  44340. else {
  44341. _super.prototype._updatePosition.call(this);
  44342. }
  44343. };
  44344. FreeCamera.prototype.dispose = function () {
  44345. this.inputs.clear();
  44346. _super.prototype.dispose.call(this);
  44347. };
  44348. FreeCamera.prototype.getClassName = function () {
  44349. return "FreeCamera";
  44350. };
  44351. __decorate([
  44352. BABYLON.serializeAsVector3()
  44353. ], FreeCamera.prototype, "ellipsoid", void 0);
  44354. __decorate([
  44355. BABYLON.serializeAsVector3()
  44356. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  44357. __decorate([
  44358. BABYLON.serialize()
  44359. ], FreeCamera.prototype, "checkCollisions", void 0);
  44360. __decorate([
  44361. BABYLON.serialize()
  44362. ], FreeCamera.prototype, "applyGravity", void 0);
  44363. return FreeCamera;
  44364. }(BABYLON.TargetCamera));
  44365. BABYLON.FreeCamera = FreeCamera;
  44366. })(BABYLON || (BABYLON = {}));
  44367. //# sourceMappingURL=babylon.freeCamera.js.map
  44368. "use strict";
  44369. var BABYLON;
  44370. (function (BABYLON) {
  44371. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  44372. function ArcRotateCameraKeyboardMoveInput() {
  44373. this._keys = new Array();
  44374. this.keysUp = [38];
  44375. this.keysDown = [40];
  44376. this.keysLeft = [37];
  44377. this.keysRight = [39];
  44378. this.keysReset = [220];
  44379. this.panningSensibility = 50.0;
  44380. this.zoomingSensibility = 25.0;
  44381. this.useAltToZoom = true;
  44382. }
  44383. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44384. var _this = this;
  44385. if (this._onCanvasBlurObserver) {
  44386. return;
  44387. }
  44388. this._scene = this.camera.getScene();
  44389. this._engine = this._scene.getEngine();
  44390. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44391. _this._keys = [];
  44392. });
  44393. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44394. var evt = info.event;
  44395. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44396. _this._ctrlPressed = evt.ctrlKey;
  44397. _this._altPressed = evt.altKey;
  44398. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44399. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44400. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44401. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44402. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44403. var index = _this._keys.indexOf(evt.keyCode);
  44404. if (index === -1) {
  44405. _this._keys.push(evt.keyCode);
  44406. }
  44407. if (evt.preventDefault) {
  44408. if (!noPreventDefault) {
  44409. evt.preventDefault();
  44410. }
  44411. }
  44412. }
  44413. }
  44414. else {
  44415. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44416. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44417. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44418. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44419. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44420. var index = _this._keys.indexOf(evt.keyCode);
  44421. if (index >= 0) {
  44422. _this._keys.splice(index, 1);
  44423. }
  44424. if (evt.preventDefault) {
  44425. if (!noPreventDefault) {
  44426. evt.preventDefault();
  44427. }
  44428. }
  44429. }
  44430. }
  44431. });
  44432. };
  44433. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44434. if (this._scene) {
  44435. if (this._onKeyboardObserver) {
  44436. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44437. }
  44438. if (this._onCanvasBlurObserver) {
  44439. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44440. }
  44441. this._onKeyboardObserver = null;
  44442. this._onCanvasBlurObserver = null;
  44443. }
  44444. this._keys = [];
  44445. };
  44446. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44447. if (this._onKeyboardObserver) {
  44448. var camera = this.camera;
  44449. for (var index = 0; index < this._keys.length; index++) {
  44450. var keyCode = this._keys[index];
  44451. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44452. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44453. camera.inertialPanningX -= 1 / this.panningSensibility;
  44454. }
  44455. else {
  44456. camera.inertialAlphaOffset -= 0.01;
  44457. }
  44458. }
  44459. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44460. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44461. camera.inertialPanningY += 1 / this.panningSensibility;
  44462. }
  44463. else if (this._altPressed && this.useAltToZoom) {
  44464. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  44465. }
  44466. else {
  44467. camera.inertialBetaOffset -= 0.01;
  44468. }
  44469. }
  44470. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44471. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44472. camera.inertialPanningX += 1 / this.panningSensibility;
  44473. }
  44474. else {
  44475. camera.inertialAlphaOffset += 0.01;
  44476. }
  44477. }
  44478. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44479. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44480. camera.inertialPanningY -= 1 / this.panningSensibility;
  44481. }
  44482. else if (this._altPressed && this.useAltToZoom) {
  44483. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  44484. }
  44485. else {
  44486. camera.inertialBetaOffset += 0.01;
  44487. }
  44488. }
  44489. else if (this.keysReset.indexOf(keyCode) !== -1) {
  44490. camera.restoreState();
  44491. }
  44492. }
  44493. }
  44494. };
  44495. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  44496. return "ArcRotateCameraKeyboardMoveInput";
  44497. };
  44498. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44499. return "keyboard";
  44500. };
  44501. __decorate([
  44502. BABYLON.serialize()
  44503. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44504. __decorate([
  44505. BABYLON.serialize()
  44506. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44507. __decorate([
  44508. BABYLON.serialize()
  44509. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44510. __decorate([
  44511. BABYLON.serialize()
  44512. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44513. __decorate([
  44514. BABYLON.serialize()
  44515. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  44516. __decorate([
  44517. BABYLON.serialize()
  44518. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  44519. __decorate([
  44520. BABYLON.serialize()
  44521. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  44522. __decorate([
  44523. BABYLON.serialize()
  44524. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  44525. return ArcRotateCameraKeyboardMoveInput;
  44526. }());
  44527. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  44528. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  44529. })(BABYLON || (BABYLON = {}));
  44530. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  44531. "use strict";
  44532. var BABYLON;
  44533. (function (BABYLON) {
  44534. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  44535. function ArcRotateCameraMouseWheelInput() {
  44536. this.wheelPrecision = 3.0;
  44537. /**
  44538. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  44539. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  44540. */
  44541. this.wheelDeltaPercentage = 0;
  44542. }
  44543. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  44544. var _this = this;
  44545. this._wheel = function (p, s) {
  44546. //sanity check - this should be a PointerWheel event.
  44547. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  44548. return;
  44549. var event = p.event;
  44550. var delta = 0;
  44551. if (event.wheelDelta) {
  44552. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  44553. }
  44554. else if (event.detail) {
  44555. delta = -event.detail / _this.wheelPrecision;
  44556. }
  44557. if (delta)
  44558. _this.camera.inertialRadiusOffset += delta;
  44559. if (event.preventDefault) {
  44560. if (!noPreventDefault) {
  44561. event.preventDefault();
  44562. }
  44563. }
  44564. };
  44565. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  44566. };
  44567. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  44568. if (this._observer && element) {
  44569. this.camera.getScene().onPointerObservable.remove(this._observer);
  44570. this._observer = null;
  44571. this._wheel = null;
  44572. }
  44573. };
  44574. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  44575. return "ArcRotateCameraMouseWheelInput";
  44576. };
  44577. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  44578. return "mousewheel";
  44579. };
  44580. __decorate([
  44581. BABYLON.serialize()
  44582. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  44583. __decorate([
  44584. BABYLON.serialize()
  44585. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  44586. return ArcRotateCameraMouseWheelInput;
  44587. }());
  44588. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  44589. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  44590. })(BABYLON || (BABYLON = {}));
  44591. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  44592. "use strict";
  44593. var BABYLON;
  44594. (function (BABYLON) {
  44595. var ArcRotateCameraPointersInput = /** @class */ (function () {
  44596. function ArcRotateCameraPointersInput() {
  44597. this.buttons = [0, 1, 2];
  44598. this.angularSensibilityX = 1000.0;
  44599. this.angularSensibilityY = 1000.0;
  44600. this.pinchPrecision = 12.0;
  44601. /**
  44602. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  44603. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  44604. */
  44605. this.pinchDeltaPercentage = 0;
  44606. this.panningSensibility = 1000.0;
  44607. this.multiTouchPanning = true;
  44608. this.multiTouchPanAndZoom = true;
  44609. this._isPanClick = false;
  44610. this.pinchInwards = true;
  44611. }
  44612. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  44613. var _this = this;
  44614. var engine = this.camera.getEngine();
  44615. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  44616. var pointA = null;
  44617. var pointB = null;
  44618. var previousPinchSquaredDistance = 0;
  44619. var initialDistance = 0;
  44620. var twoFingerActivityCount = 0;
  44621. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  44622. this._pointerInput = function (p, s) {
  44623. var evt = p.event;
  44624. var isTouch = p.event.pointerType === "touch";
  44625. if (engine.isInVRExclusivePointerMode) {
  44626. return;
  44627. }
  44628. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44629. return;
  44630. }
  44631. var srcElement = (evt.srcElement || evt.target);
  44632. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44633. try {
  44634. srcElement.setPointerCapture(evt.pointerId);
  44635. }
  44636. catch (e) {
  44637. //Nothing to do with the error. Execution will continue.
  44638. }
  44639. // Manage panning with pan button click
  44640. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44641. // manage pointers
  44642. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44643. if (pointA === null) {
  44644. pointA = cacheSoloPointer;
  44645. }
  44646. else if (pointB === null) {
  44647. pointB = cacheSoloPointer;
  44648. }
  44649. if (!noPreventDefault) {
  44650. evt.preventDefault();
  44651. element.focus();
  44652. }
  44653. }
  44654. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44655. _this.camera.restoreState();
  44656. }
  44657. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44658. try {
  44659. srcElement.releasePointerCapture(evt.pointerId);
  44660. }
  44661. catch (e) {
  44662. //Nothing to do with the error.
  44663. }
  44664. cacheSoloPointer = null;
  44665. previousPinchSquaredDistance = 0;
  44666. previousMultiTouchPanPosition.isPaning = false;
  44667. previousMultiTouchPanPosition.isPinching = false;
  44668. twoFingerActivityCount = 0;
  44669. initialDistance = 0;
  44670. if (!isTouch) {
  44671. pointB = null; // Mouse and pen are mono pointer
  44672. }
  44673. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44674. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44675. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44676. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44677. if (engine.badOS) {
  44678. pointA = pointB = null;
  44679. }
  44680. else {
  44681. //only remove the impacted pointer in case of multitouch allowing on most
  44682. //platforms switching from rotate to zoom and pan seamlessly.
  44683. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44684. pointA = pointB;
  44685. pointB = null;
  44686. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44687. }
  44688. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44689. pointB = null;
  44690. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44691. }
  44692. else {
  44693. pointA = pointB = null;
  44694. }
  44695. }
  44696. if (!noPreventDefault) {
  44697. evt.preventDefault();
  44698. }
  44699. }
  44700. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44701. if (!noPreventDefault) {
  44702. evt.preventDefault();
  44703. }
  44704. // One button down
  44705. if (pointA && pointB === null && cacheSoloPointer) {
  44706. if (_this.panningSensibility !== 0 &&
  44707. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44708. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44709. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44710. }
  44711. else {
  44712. var offsetX = evt.clientX - cacheSoloPointer.x;
  44713. var offsetY = evt.clientY - cacheSoloPointer.y;
  44714. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44715. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44716. }
  44717. cacheSoloPointer.x = evt.clientX;
  44718. cacheSoloPointer.y = evt.clientY;
  44719. }
  44720. else if (pointA && pointB) {
  44721. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44722. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44723. ed.x = evt.clientX;
  44724. ed.y = evt.clientY;
  44725. var direction = _this.pinchInwards ? 1 : -1;
  44726. var distX = pointA.x - pointB.x;
  44727. var distY = pointA.y - pointB.y;
  44728. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44729. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44730. if (previousPinchSquaredDistance === 0) {
  44731. initialDistance = pinchDistance;
  44732. previousPinchSquaredDistance = pinchSquaredDistance;
  44733. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44734. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44735. return;
  44736. }
  44737. if (_this.multiTouchPanAndZoom) {
  44738. if (_this.pinchDeltaPercentage) {
  44739. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44740. }
  44741. else {
  44742. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44743. (_this.pinchPrecision *
  44744. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44745. direction);
  44746. }
  44747. if (_this.panningSensibility !== 0) {
  44748. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44749. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44750. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44751. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44752. previousMultiTouchPanPosition.x = pointersCenterX;
  44753. previousMultiTouchPanPosition.y = pointersCenterY;
  44754. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44755. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44756. }
  44757. }
  44758. else {
  44759. twoFingerActivityCount++;
  44760. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44761. if (_this.pinchDeltaPercentage) {
  44762. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44763. }
  44764. else {
  44765. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44766. (_this.pinchPrecision *
  44767. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44768. direction);
  44769. }
  44770. previousMultiTouchPanPosition.isPaning = false;
  44771. previousMultiTouchPanPosition.isPinching = true;
  44772. }
  44773. else {
  44774. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44775. if (!previousMultiTouchPanPosition.isPaning) {
  44776. previousMultiTouchPanPosition.isPaning = true;
  44777. previousMultiTouchPanPosition.isPinching = false;
  44778. previousMultiTouchPanPosition.x = ed.x;
  44779. previousMultiTouchPanPosition.y = ed.y;
  44780. return;
  44781. }
  44782. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44783. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44784. }
  44785. }
  44786. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44787. previousMultiTouchPanPosition.x = ed.x;
  44788. previousMultiTouchPanPosition.y = ed.y;
  44789. }
  44790. }
  44791. previousPinchSquaredDistance = pinchSquaredDistance;
  44792. }
  44793. }
  44794. };
  44795. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44796. this._onContextMenu = function (evt) {
  44797. evt.preventDefault();
  44798. };
  44799. if (!this.camera._useCtrlForPanning) {
  44800. element.addEventListener("contextmenu", this._onContextMenu, false);
  44801. }
  44802. this._onLostFocus = function () {
  44803. //this._keys = [];
  44804. pointA = pointB = null;
  44805. previousPinchSquaredDistance = 0;
  44806. previousMultiTouchPanPosition.isPaning = false;
  44807. previousMultiTouchPanPosition.isPinching = false;
  44808. twoFingerActivityCount = 0;
  44809. cacheSoloPointer = null;
  44810. initialDistance = 0;
  44811. };
  44812. this._onMouseMove = function (evt) {
  44813. if (!engine.isPointerLock) {
  44814. return;
  44815. }
  44816. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44817. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44818. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44819. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44820. if (!noPreventDefault) {
  44821. evt.preventDefault();
  44822. }
  44823. };
  44824. this._onGestureStart = function (e) {
  44825. if (window.MSGesture === undefined) {
  44826. return;
  44827. }
  44828. if (!_this._MSGestureHandler) {
  44829. _this._MSGestureHandler = new MSGesture();
  44830. _this._MSGestureHandler.target = element;
  44831. }
  44832. _this._MSGestureHandler.addPointer(e.pointerId);
  44833. };
  44834. this._onGesture = function (e) {
  44835. _this.camera.radius *= e.scale;
  44836. if (e.preventDefault) {
  44837. if (!noPreventDefault) {
  44838. e.stopPropagation();
  44839. e.preventDefault();
  44840. }
  44841. }
  44842. };
  44843. element.addEventListener("mousemove", this._onMouseMove, false);
  44844. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44845. element.addEventListener("MSGestureChange", this._onGesture, false);
  44846. BABYLON.Tools.RegisterTopRootEvents([
  44847. { name: "blur", handler: this._onLostFocus }
  44848. ]);
  44849. };
  44850. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44851. if (this._onLostFocus) {
  44852. BABYLON.Tools.UnregisterTopRootEvents([
  44853. { name: "blur", handler: this._onLostFocus }
  44854. ]);
  44855. }
  44856. if (element && this._observer) {
  44857. this.camera.getScene().onPointerObservable.remove(this._observer);
  44858. this._observer = null;
  44859. if (this._onContextMenu) {
  44860. element.removeEventListener("contextmenu", this._onContextMenu);
  44861. }
  44862. if (this._onMouseMove) {
  44863. element.removeEventListener("mousemove", this._onMouseMove);
  44864. }
  44865. if (this._onGestureStart) {
  44866. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44867. }
  44868. if (this._onGesture) {
  44869. element.removeEventListener("MSGestureChange", this._onGesture);
  44870. }
  44871. this._isPanClick = false;
  44872. this.pinchInwards = true;
  44873. this._onMouseMove = null;
  44874. this._onGestureStart = null;
  44875. this._onGesture = null;
  44876. this._MSGestureHandler = null;
  44877. this._onLostFocus = null;
  44878. this._onContextMenu = null;
  44879. }
  44880. };
  44881. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44882. return "ArcRotateCameraPointersInput";
  44883. };
  44884. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44885. return "pointers";
  44886. };
  44887. __decorate([
  44888. BABYLON.serialize()
  44889. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44890. __decorate([
  44891. BABYLON.serialize()
  44892. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44893. __decorate([
  44894. BABYLON.serialize()
  44895. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44896. __decorate([
  44897. BABYLON.serialize()
  44898. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44899. __decorate([
  44900. BABYLON.serialize()
  44901. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44902. __decorate([
  44903. BABYLON.serialize()
  44904. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44905. __decorate([
  44906. BABYLON.serialize()
  44907. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44908. __decorate([
  44909. BABYLON.serialize()
  44910. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44911. return ArcRotateCameraPointersInput;
  44912. }());
  44913. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44914. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44915. })(BABYLON || (BABYLON = {}));
  44916. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44917. "use strict";
  44918. var BABYLON;
  44919. (function (BABYLON) {
  44920. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44921. __extends(ArcRotateCameraInputsManager, _super);
  44922. function ArcRotateCameraInputsManager(camera) {
  44923. return _super.call(this, camera) || this;
  44924. }
  44925. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44926. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44927. return this;
  44928. };
  44929. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  44930. this.add(new BABYLON.ArcRotateCameraPointersInput());
  44931. return this;
  44932. };
  44933. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  44934. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  44935. return this;
  44936. };
  44937. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  44938. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  44939. return this;
  44940. };
  44941. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  44942. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  44943. return this;
  44944. };
  44945. return ArcRotateCameraInputsManager;
  44946. }(BABYLON.CameraInputsManager));
  44947. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  44948. })(BABYLON || (BABYLON = {}));
  44949. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  44950. "use strict";
  44951. var BABYLON;
  44952. (function (BABYLON) {
  44953. var ArcRotateCamera = /** @class */ (function (_super) {
  44954. __extends(ArcRotateCamera, _super);
  44955. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  44956. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  44957. _this.inertialAlphaOffset = 0;
  44958. _this.inertialBetaOffset = 0;
  44959. _this.inertialRadiusOffset = 0;
  44960. _this.lowerAlphaLimit = null;
  44961. _this.upperAlphaLimit = null;
  44962. _this.lowerBetaLimit = 0.01;
  44963. _this.upperBetaLimit = Math.PI;
  44964. _this.lowerRadiusLimit = null;
  44965. _this.upperRadiusLimit = null;
  44966. _this.inertialPanningX = 0;
  44967. _this.inertialPanningY = 0;
  44968. _this.pinchToPanMaxDistance = 20;
  44969. _this.panningDistanceLimit = null;
  44970. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  44971. _this.panningInertia = 0.9;
  44972. //-- end properties for backward compatibility for inputs
  44973. _this.zoomOnFactor = 1;
  44974. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  44975. _this.allowUpsideDown = true;
  44976. _this._viewMatrix = new BABYLON.Matrix();
  44977. // Panning
  44978. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  44979. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  44980. _this.checkCollisions = false;
  44981. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44982. _this._previousPosition = BABYLON.Vector3.Zero();
  44983. _this._collisionVelocity = BABYLON.Vector3.Zero();
  44984. _this._newPosition = BABYLON.Vector3.Zero();
  44985. _this._computationVector = BABYLON.Vector3.Zero();
  44986. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44987. if (collidedMesh === void 0) { collidedMesh = null; }
  44988. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  44989. newPosition.multiplyInPlace(_this._collider._radius);
  44990. }
  44991. if (!collidedMesh) {
  44992. _this._previousPosition.copyFrom(_this.position);
  44993. }
  44994. else {
  44995. _this.setPosition(newPosition);
  44996. if (_this.onCollide) {
  44997. _this.onCollide(collidedMesh);
  44998. }
  44999. }
  45000. // Recompute because of constraints
  45001. var cosa = Math.cos(_this.alpha);
  45002. var sina = Math.sin(_this.alpha);
  45003. var cosb = Math.cos(_this.beta);
  45004. var sinb = Math.sin(_this.beta);
  45005. if (sinb === 0) {
  45006. sinb = 0.0001;
  45007. }
  45008. var target = _this._getTargetPosition();
  45009. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  45010. target.addToRef(_this._computationVector, _this._newPosition);
  45011. _this.position.copyFrom(_this._newPosition);
  45012. var up = _this.upVector;
  45013. if (_this.allowUpsideDown && _this.beta < 0) {
  45014. up = up.clone();
  45015. up = up.negate();
  45016. }
  45017. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  45018. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  45019. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  45020. _this._collisionTriggered = false;
  45021. };
  45022. _this._target = BABYLON.Vector3.Zero();
  45023. if (target) {
  45024. _this.setTarget(target);
  45025. }
  45026. _this.alpha = alpha;
  45027. _this.beta = beta;
  45028. _this.radius = radius;
  45029. _this.getViewMatrix();
  45030. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  45031. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  45032. return _this;
  45033. }
  45034. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  45035. get: function () {
  45036. return this._target;
  45037. },
  45038. set: function (value) {
  45039. this.setTarget(value);
  45040. },
  45041. enumerable: true,
  45042. configurable: true
  45043. });
  45044. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  45045. //-- begin properties for backward compatibility for inputs
  45046. get: function () {
  45047. var pointers = this.inputs.attached["pointers"];
  45048. if (pointers)
  45049. return pointers.angularSensibilityX;
  45050. return 0;
  45051. },
  45052. set: function (value) {
  45053. var pointers = this.inputs.attached["pointers"];
  45054. if (pointers) {
  45055. pointers.angularSensibilityX = value;
  45056. }
  45057. },
  45058. enumerable: true,
  45059. configurable: true
  45060. });
  45061. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  45062. get: function () {
  45063. var pointers = this.inputs.attached["pointers"];
  45064. if (pointers)
  45065. return pointers.angularSensibilityY;
  45066. return 0;
  45067. },
  45068. set: function (value) {
  45069. var pointers = this.inputs.attached["pointers"];
  45070. if (pointers) {
  45071. pointers.angularSensibilityY = value;
  45072. }
  45073. },
  45074. enumerable: true,
  45075. configurable: true
  45076. });
  45077. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  45078. get: function () {
  45079. var pointers = this.inputs.attached["pointers"];
  45080. if (pointers)
  45081. return pointers.pinchPrecision;
  45082. return 0;
  45083. },
  45084. set: function (value) {
  45085. var pointers = this.inputs.attached["pointers"];
  45086. if (pointers) {
  45087. pointers.pinchPrecision = value;
  45088. }
  45089. },
  45090. enumerable: true,
  45091. configurable: true
  45092. });
  45093. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  45094. get: function () {
  45095. var pointers = this.inputs.attached["pointers"];
  45096. if (pointers)
  45097. return pointers.pinchDeltaPercentage;
  45098. return 0;
  45099. },
  45100. set: function (value) {
  45101. var pointers = this.inputs.attached["pointers"];
  45102. if (pointers) {
  45103. pointers.pinchDeltaPercentage = value;
  45104. }
  45105. },
  45106. enumerable: true,
  45107. configurable: true
  45108. });
  45109. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  45110. get: function () {
  45111. var pointers = this.inputs.attached["pointers"];
  45112. if (pointers)
  45113. return pointers.panningSensibility;
  45114. return 0;
  45115. },
  45116. set: function (value) {
  45117. var pointers = this.inputs.attached["pointers"];
  45118. if (pointers) {
  45119. pointers.panningSensibility = value;
  45120. }
  45121. },
  45122. enumerable: true,
  45123. configurable: true
  45124. });
  45125. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  45126. get: function () {
  45127. var keyboard = this.inputs.attached["keyboard"];
  45128. if (keyboard)
  45129. return keyboard.keysUp;
  45130. return [];
  45131. },
  45132. set: function (value) {
  45133. var keyboard = this.inputs.attached["keyboard"];
  45134. if (keyboard)
  45135. keyboard.keysUp = value;
  45136. },
  45137. enumerable: true,
  45138. configurable: true
  45139. });
  45140. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  45141. get: function () {
  45142. var keyboard = this.inputs.attached["keyboard"];
  45143. if (keyboard)
  45144. return keyboard.keysDown;
  45145. return [];
  45146. },
  45147. set: function (value) {
  45148. var keyboard = this.inputs.attached["keyboard"];
  45149. if (keyboard)
  45150. keyboard.keysDown = value;
  45151. },
  45152. enumerable: true,
  45153. configurable: true
  45154. });
  45155. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  45156. get: function () {
  45157. var keyboard = this.inputs.attached["keyboard"];
  45158. if (keyboard)
  45159. return keyboard.keysLeft;
  45160. return [];
  45161. },
  45162. set: function (value) {
  45163. var keyboard = this.inputs.attached["keyboard"];
  45164. if (keyboard)
  45165. keyboard.keysLeft = value;
  45166. },
  45167. enumerable: true,
  45168. configurable: true
  45169. });
  45170. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  45171. get: function () {
  45172. var keyboard = this.inputs.attached["keyboard"];
  45173. if (keyboard)
  45174. return keyboard.keysRight;
  45175. return [];
  45176. },
  45177. set: function (value) {
  45178. var keyboard = this.inputs.attached["keyboard"];
  45179. if (keyboard)
  45180. keyboard.keysRight = value;
  45181. },
  45182. enumerable: true,
  45183. configurable: true
  45184. });
  45185. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  45186. get: function () {
  45187. var mousewheel = this.inputs.attached["mousewheel"];
  45188. if (mousewheel)
  45189. return mousewheel.wheelPrecision;
  45190. return 0;
  45191. },
  45192. set: function (value) {
  45193. var mousewheel = this.inputs.attached["mousewheel"];
  45194. if (mousewheel)
  45195. mousewheel.wheelPrecision = value;
  45196. },
  45197. enumerable: true,
  45198. configurable: true
  45199. });
  45200. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  45201. get: function () {
  45202. var mousewheel = this.inputs.attached["mousewheel"];
  45203. if (mousewheel)
  45204. return mousewheel.wheelDeltaPercentage;
  45205. return 0;
  45206. },
  45207. set: function (value) {
  45208. var mousewheel = this.inputs.attached["mousewheel"];
  45209. if (mousewheel)
  45210. mousewheel.wheelDeltaPercentage = value;
  45211. },
  45212. enumerable: true,
  45213. configurable: true
  45214. });
  45215. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  45216. get: function () {
  45217. return this._bouncingBehavior;
  45218. },
  45219. enumerable: true,
  45220. configurable: true
  45221. });
  45222. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  45223. get: function () {
  45224. return this._bouncingBehavior != null;
  45225. },
  45226. set: function (value) {
  45227. if (value === this.useBouncingBehavior) {
  45228. return;
  45229. }
  45230. if (value) {
  45231. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  45232. this.addBehavior(this._bouncingBehavior);
  45233. }
  45234. else if (this._bouncingBehavior) {
  45235. this.removeBehavior(this._bouncingBehavior);
  45236. this._bouncingBehavior = null;
  45237. }
  45238. },
  45239. enumerable: true,
  45240. configurable: true
  45241. });
  45242. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  45243. get: function () {
  45244. return this._framingBehavior;
  45245. },
  45246. enumerable: true,
  45247. configurable: true
  45248. });
  45249. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  45250. get: function () {
  45251. return this._framingBehavior != null;
  45252. },
  45253. set: function (value) {
  45254. if (value === this.useFramingBehavior) {
  45255. return;
  45256. }
  45257. if (value) {
  45258. this._framingBehavior = new BABYLON.FramingBehavior();
  45259. this.addBehavior(this._framingBehavior);
  45260. }
  45261. else if (this._framingBehavior) {
  45262. this.removeBehavior(this._framingBehavior);
  45263. this._framingBehavior = null;
  45264. }
  45265. },
  45266. enumerable: true,
  45267. configurable: true
  45268. });
  45269. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  45270. get: function () {
  45271. return this._autoRotationBehavior;
  45272. },
  45273. enumerable: true,
  45274. configurable: true
  45275. });
  45276. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  45277. get: function () {
  45278. return this._autoRotationBehavior != null;
  45279. },
  45280. set: function (value) {
  45281. if (value === this.useAutoRotationBehavior) {
  45282. return;
  45283. }
  45284. if (value) {
  45285. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  45286. this.addBehavior(this._autoRotationBehavior);
  45287. }
  45288. else if (this._autoRotationBehavior) {
  45289. this.removeBehavior(this._autoRotationBehavior);
  45290. this._autoRotationBehavior = null;
  45291. }
  45292. },
  45293. enumerable: true,
  45294. configurable: true
  45295. });
  45296. // Cache
  45297. ArcRotateCamera.prototype._initCache = function () {
  45298. _super.prototype._initCache.call(this);
  45299. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45300. this._cache.alpha = undefined;
  45301. this._cache.beta = undefined;
  45302. this._cache.radius = undefined;
  45303. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  45304. };
  45305. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  45306. if (!ignoreParentClass) {
  45307. _super.prototype._updateCache.call(this);
  45308. }
  45309. this._cache._target.copyFrom(this._getTargetPosition());
  45310. this._cache.alpha = this.alpha;
  45311. this._cache.beta = this.beta;
  45312. this._cache.radius = this.radius;
  45313. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  45314. };
  45315. ArcRotateCamera.prototype._getTargetPosition = function () {
  45316. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  45317. var pos = this._targetHost.getAbsolutePosition();
  45318. if (this._targetBoundingCenter) {
  45319. pos.addToRef(this._targetBoundingCenter, this._target);
  45320. }
  45321. else {
  45322. this._target.copyFrom(pos);
  45323. }
  45324. }
  45325. var lockedTargetPosition = this._getLockedTargetPosition();
  45326. if (lockedTargetPosition) {
  45327. return lockedTargetPosition;
  45328. }
  45329. return this._target;
  45330. };
  45331. ArcRotateCamera.prototype.storeState = function () {
  45332. this._storedAlpha = this.alpha;
  45333. this._storedBeta = this.beta;
  45334. this._storedRadius = this.radius;
  45335. this._storedTarget = this._getTargetPosition().clone();
  45336. return _super.prototype.storeState.call(this);
  45337. };
  45338. /**
  45339. * Restored camera state. You must call storeState() first
  45340. */
  45341. ArcRotateCamera.prototype._restoreStateValues = function () {
  45342. if (!_super.prototype._restoreStateValues.call(this)) {
  45343. return false;
  45344. }
  45345. this.alpha = this._storedAlpha;
  45346. this.beta = this._storedBeta;
  45347. this.radius = this._storedRadius;
  45348. this.setTarget(this._storedTarget.clone());
  45349. this.inertialAlphaOffset = 0;
  45350. this.inertialBetaOffset = 0;
  45351. this.inertialRadiusOffset = 0;
  45352. this.inertialPanningX = 0;
  45353. this.inertialPanningY = 0;
  45354. return true;
  45355. };
  45356. // Synchronized
  45357. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  45358. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  45359. return false;
  45360. return this._cache._target.equals(this._getTargetPosition())
  45361. && this._cache.alpha === this.alpha
  45362. && this._cache.beta === this.beta
  45363. && this._cache.radius === this.radius
  45364. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  45365. };
  45366. // Methods
  45367. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  45368. var _this = this;
  45369. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  45370. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  45371. this._useCtrlForPanning = useCtrlForPanning;
  45372. this._panningMouseButton = panningMouseButton;
  45373. this.inputs.attachElement(element, noPreventDefault);
  45374. this._reset = function () {
  45375. _this.inertialAlphaOffset = 0;
  45376. _this.inertialBetaOffset = 0;
  45377. _this.inertialRadiusOffset = 0;
  45378. _this.inertialPanningX = 0;
  45379. _this.inertialPanningY = 0;
  45380. };
  45381. };
  45382. ArcRotateCamera.prototype.detachControl = function (element) {
  45383. this.inputs.detachElement(element);
  45384. if (this._reset) {
  45385. this._reset();
  45386. }
  45387. };
  45388. ArcRotateCamera.prototype._checkInputs = function () {
  45389. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  45390. if (this._collisionTriggered) {
  45391. return;
  45392. }
  45393. this.inputs.checkInputs();
  45394. // Inertia
  45395. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  45396. if (this.getScene().useRightHandedSystem) {
  45397. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45398. }
  45399. else {
  45400. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45401. }
  45402. this.beta += this.inertialBetaOffset;
  45403. this.radius -= this.inertialRadiusOffset;
  45404. this.inertialAlphaOffset *= this.inertia;
  45405. this.inertialBetaOffset *= this.inertia;
  45406. this.inertialRadiusOffset *= this.inertia;
  45407. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  45408. this.inertialAlphaOffset = 0;
  45409. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  45410. this.inertialBetaOffset = 0;
  45411. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  45412. this.inertialRadiusOffset = 0;
  45413. }
  45414. // Panning inertia
  45415. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  45416. if (!this._localDirection) {
  45417. this._localDirection = BABYLON.Vector3.Zero();
  45418. this._transformedDirection = BABYLON.Vector3.Zero();
  45419. }
  45420. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  45421. this._localDirection.multiplyInPlace(this.panningAxis);
  45422. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  45423. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  45424. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  45425. if (!this.panningAxis.y) {
  45426. this._transformedDirection.y = 0;
  45427. }
  45428. if (!this._targetHost) {
  45429. if (this.panningDistanceLimit) {
  45430. this._transformedDirection.addInPlace(this._target);
  45431. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  45432. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  45433. this._target.copyFrom(this._transformedDirection);
  45434. }
  45435. }
  45436. else {
  45437. this._target.addInPlace(this._transformedDirection);
  45438. }
  45439. }
  45440. this.inertialPanningX *= this.panningInertia;
  45441. this.inertialPanningY *= this.panningInertia;
  45442. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  45443. this.inertialPanningX = 0;
  45444. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  45445. this.inertialPanningY = 0;
  45446. }
  45447. // Limits
  45448. this._checkLimits();
  45449. _super.prototype._checkInputs.call(this);
  45450. };
  45451. ArcRotateCamera.prototype._checkLimits = function () {
  45452. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  45453. if (this.allowUpsideDown && this.beta > Math.PI) {
  45454. this.beta = this.beta - (2 * Math.PI);
  45455. }
  45456. }
  45457. else {
  45458. if (this.beta < this.lowerBetaLimit) {
  45459. this.beta = this.lowerBetaLimit;
  45460. }
  45461. }
  45462. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  45463. if (this.allowUpsideDown && this.beta < -Math.PI) {
  45464. this.beta = this.beta + (2 * Math.PI);
  45465. }
  45466. }
  45467. else {
  45468. if (this.beta > this.upperBetaLimit) {
  45469. this.beta = this.upperBetaLimit;
  45470. }
  45471. }
  45472. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  45473. this.alpha = this.lowerAlphaLimit;
  45474. }
  45475. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  45476. this.alpha = this.upperAlphaLimit;
  45477. }
  45478. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  45479. this.radius = this.lowerRadiusLimit;
  45480. }
  45481. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  45482. this.radius = this.upperRadiusLimit;
  45483. }
  45484. };
  45485. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  45486. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  45487. this.radius = this._computationVector.length();
  45488. if (this.radius === 0) {
  45489. this.radius = 0.0001; // Just to avoid division by zero
  45490. }
  45491. // Alpha
  45492. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  45493. if (this._computationVector.z < 0) {
  45494. this.alpha = 2 * Math.PI - this.alpha;
  45495. }
  45496. // Beta
  45497. this.beta = Math.acos(this._computationVector.y / this.radius);
  45498. this._checkLimits();
  45499. };
  45500. ArcRotateCamera.prototype.setPosition = function (position) {
  45501. if (this.position.equals(position)) {
  45502. return;
  45503. }
  45504. this.position.copyFrom(position);
  45505. this.rebuildAnglesAndRadius();
  45506. };
  45507. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  45508. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  45509. if (allowSamePosition === void 0) { allowSamePosition = false; }
  45510. if (target.getBoundingInfo) {
  45511. if (toBoundingCenter) {
  45512. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  45513. }
  45514. else {
  45515. this._targetBoundingCenter = null;
  45516. }
  45517. this._targetHost = target;
  45518. this._target = this._getTargetPosition();
  45519. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  45520. }
  45521. else {
  45522. var newTarget = target;
  45523. var currentTarget = this._getTargetPosition();
  45524. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  45525. return;
  45526. }
  45527. this._targetHost = null;
  45528. this._target = newTarget;
  45529. this._targetBoundingCenter = null;
  45530. this.onMeshTargetChangedObservable.notifyObservers(null);
  45531. }
  45532. this.rebuildAnglesAndRadius();
  45533. };
  45534. ArcRotateCamera.prototype._getViewMatrix = function () {
  45535. // Compute
  45536. var cosa = Math.cos(this.alpha);
  45537. var sina = Math.sin(this.alpha);
  45538. var cosb = Math.cos(this.beta);
  45539. var sinb = Math.sin(this.beta);
  45540. if (sinb === 0) {
  45541. sinb = 0.0001;
  45542. }
  45543. var target = this._getTargetPosition();
  45544. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  45545. target.addToRef(this._computationVector, this._newPosition);
  45546. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  45547. if (!this._collider) {
  45548. this._collider = new BABYLON.Collider();
  45549. }
  45550. this._collider._radius = this.collisionRadius;
  45551. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  45552. this._collisionTriggered = true;
  45553. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  45554. }
  45555. else {
  45556. this.position.copyFrom(this._newPosition);
  45557. var up = this.upVector;
  45558. if (this.allowUpsideDown && sinb < 0) {
  45559. up = up.clone();
  45560. up = up.negate();
  45561. }
  45562. if (this.getScene().useRightHandedSystem) {
  45563. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  45564. }
  45565. else {
  45566. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  45567. }
  45568. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  45569. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  45570. }
  45571. this._currentTarget = target;
  45572. return this._viewMatrix;
  45573. };
  45574. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  45575. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45576. meshes = meshes || this.getScene().meshes;
  45577. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  45578. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  45579. this.radius = distance * this.zoomOnFactor;
  45580. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  45581. };
  45582. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  45583. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45584. var meshesOrMinMaxVector;
  45585. var distance;
  45586. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  45587. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  45588. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  45589. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  45590. }
  45591. else {
  45592. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  45593. meshesOrMinMaxVector = minMaxVectorAndDistance;
  45594. distance = minMaxVectorAndDistance.distance;
  45595. }
  45596. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  45597. if (!doNotUpdateMaxZ) {
  45598. this.maxZ = distance * 2;
  45599. }
  45600. };
  45601. /**
  45602. * @override
  45603. * Override Camera.createRigCamera
  45604. */
  45605. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45606. var alphaShift = 0;
  45607. switch (this.cameraRigMode) {
  45608. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45609. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45610. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45611. case BABYLON.Camera.RIG_MODE_VR:
  45612. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  45613. break;
  45614. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45615. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  45616. break;
  45617. }
  45618. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  45619. rigCam._cameraRigParams = {};
  45620. return rigCam;
  45621. };
  45622. /**
  45623. * @override
  45624. * Override Camera._updateRigCameras
  45625. */
  45626. ArcRotateCamera.prototype._updateRigCameras = function () {
  45627. var camLeft = this._rigCameras[0];
  45628. var camRight = this._rigCameras[1];
  45629. camLeft.beta = camRight.beta = this.beta;
  45630. camLeft.radius = camRight.radius = this.radius;
  45631. switch (this.cameraRigMode) {
  45632. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45633. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45634. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45635. case BABYLON.Camera.RIG_MODE_VR:
  45636. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45637. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45638. break;
  45639. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45640. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45641. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45642. break;
  45643. }
  45644. _super.prototype._updateRigCameras.call(this);
  45645. };
  45646. ArcRotateCamera.prototype.dispose = function () {
  45647. this.inputs.clear();
  45648. _super.prototype.dispose.call(this);
  45649. };
  45650. ArcRotateCamera.prototype.getClassName = function () {
  45651. return "ArcRotateCamera";
  45652. };
  45653. __decorate([
  45654. BABYLON.serialize()
  45655. ], ArcRotateCamera.prototype, "alpha", void 0);
  45656. __decorate([
  45657. BABYLON.serialize()
  45658. ], ArcRotateCamera.prototype, "beta", void 0);
  45659. __decorate([
  45660. BABYLON.serialize()
  45661. ], ArcRotateCamera.prototype, "radius", void 0);
  45662. __decorate([
  45663. BABYLON.serializeAsVector3("target")
  45664. ], ArcRotateCamera.prototype, "_target", void 0);
  45665. __decorate([
  45666. BABYLON.serialize()
  45667. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45668. __decorate([
  45669. BABYLON.serialize()
  45670. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45671. __decorate([
  45672. BABYLON.serialize()
  45673. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45674. __decorate([
  45675. BABYLON.serialize()
  45676. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45677. __decorate([
  45678. BABYLON.serialize()
  45679. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45680. __decorate([
  45681. BABYLON.serialize()
  45682. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45683. __decorate([
  45684. BABYLON.serialize()
  45685. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45686. __decorate([
  45687. BABYLON.serialize()
  45688. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45689. __decorate([
  45690. BABYLON.serialize()
  45691. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45692. __decorate([
  45693. BABYLON.serialize()
  45694. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45695. __decorate([
  45696. BABYLON.serialize()
  45697. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45698. __decorate([
  45699. BABYLON.serialize()
  45700. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45701. __decorate([
  45702. BABYLON.serialize()
  45703. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45704. __decorate([
  45705. BABYLON.serializeAsVector3()
  45706. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45707. __decorate([
  45708. BABYLON.serialize()
  45709. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45710. __decorate([
  45711. BABYLON.serialize()
  45712. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45713. __decorate([
  45714. BABYLON.serialize()
  45715. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45716. return ArcRotateCamera;
  45717. }(BABYLON.TargetCamera));
  45718. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45719. })(BABYLON || (BABYLON = {}));
  45720. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45721. "use strict";
  45722. var BABYLON;
  45723. (function (BABYLON) {
  45724. /**
  45725. * The HemisphericLight simulates the ambient environment light,
  45726. * so the passed direction is the light reflection direction, not the incoming direction.
  45727. */
  45728. var HemisphericLight = /** @class */ (function (_super) {
  45729. __extends(HemisphericLight, _super);
  45730. /**
  45731. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45732. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45733. * The HemisphericLight can't cast shadows.
  45734. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45735. * @param name The friendly name of the light
  45736. * @param direction The direction of the light reflection
  45737. * @param scene The scene the light belongs to
  45738. */
  45739. function HemisphericLight(name, direction, scene) {
  45740. var _this = _super.call(this, name, scene) || this;
  45741. /**
  45742. * The groundColor is the light in the opposite direction to the one specified during creation.
  45743. * 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.
  45744. */
  45745. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45746. _this.direction = direction || BABYLON.Vector3.Up();
  45747. return _this;
  45748. }
  45749. HemisphericLight.prototype._buildUniformLayout = function () {
  45750. this._uniformBuffer.addUniform("vLightData", 4);
  45751. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45752. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45753. this._uniformBuffer.addUniform("vLightGround", 3);
  45754. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45755. this._uniformBuffer.addUniform("depthValues", 2);
  45756. this._uniformBuffer.create();
  45757. };
  45758. /**
  45759. * Returns the string "HemisphericLight".
  45760. * @return The class name
  45761. */
  45762. HemisphericLight.prototype.getClassName = function () {
  45763. return "HemisphericLight";
  45764. };
  45765. /**
  45766. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45767. * Returns the updated direction.
  45768. * @param target The target the direction should point to
  45769. * @return The computed direction
  45770. */
  45771. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45772. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45773. return this.direction;
  45774. };
  45775. /**
  45776. * Returns the shadow generator associated to the light.
  45777. * @returns Always null for hemispheric lights because it does not support shadows.
  45778. */
  45779. HemisphericLight.prototype.getShadowGenerator = function () {
  45780. return null;
  45781. };
  45782. /**
  45783. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45784. * @param effect The effect to update
  45785. * @param lightIndex The index of the light in the effect to update
  45786. * @returns The hemispheric light
  45787. */
  45788. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45789. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45790. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45791. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45792. return this;
  45793. };
  45794. /**
  45795. * @ignore internal use only.
  45796. */
  45797. HemisphericLight.prototype._getWorldMatrix = function () {
  45798. if (!this._worldMatrix) {
  45799. this._worldMatrix = BABYLON.Matrix.Identity();
  45800. }
  45801. return this._worldMatrix;
  45802. };
  45803. /**
  45804. * Returns the integer 3.
  45805. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45806. */
  45807. HemisphericLight.prototype.getTypeID = function () {
  45808. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45809. };
  45810. __decorate([
  45811. BABYLON.serializeAsColor3()
  45812. ], HemisphericLight.prototype, "groundColor", void 0);
  45813. __decorate([
  45814. BABYLON.serializeAsVector3()
  45815. ], HemisphericLight.prototype, "direction", void 0);
  45816. return HemisphericLight;
  45817. }(BABYLON.Light));
  45818. BABYLON.HemisphericLight = HemisphericLight;
  45819. })(BABYLON || (BABYLON = {}));
  45820. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45821. "use strict";
  45822. var BABYLON;
  45823. (function (BABYLON) {
  45824. /**
  45825. * Base implementation of @see IShadowLight
  45826. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45827. */
  45828. var ShadowLight = /** @class */ (function (_super) {
  45829. __extends(ShadowLight, _super);
  45830. function ShadowLight() {
  45831. var _this = _super !== null && _super.apply(this, arguments) || this;
  45832. _this._needProjectionMatrixCompute = true;
  45833. return _this;
  45834. }
  45835. ShadowLight.prototype._setPosition = function (value) {
  45836. this._position = value;
  45837. };
  45838. Object.defineProperty(ShadowLight.prototype, "position", {
  45839. /**
  45840. * Sets the position the shadow will be casted from. Also use as the light position for both
  45841. * point and spot lights.
  45842. */
  45843. get: function () {
  45844. return this._position;
  45845. },
  45846. /**
  45847. * Sets the position the shadow will be casted from. Also use as the light position for both
  45848. * point and spot lights.
  45849. */
  45850. set: function (value) {
  45851. this._setPosition(value);
  45852. },
  45853. enumerable: true,
  45854. configurable: true
  45855. });
  45856. ShadowLight.prototype._setDirection = function (value) {
  45857. this._direction = value;
  45858. };
  45859. Object.defineProperty(ShadowLight.prototype, "direction", {
  45860. /**
  45861. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45862. * Also use as the light direction on spot and directional lights.
  45863. */
  45864. get: function () {
  45865. return this._direction;
  45866. },
  45867. /**
  45868. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45869. * Also use as the light direction on spot and directional lights.
  45870. */
  45871. set: function (value) {
  45872. this._setDirection(value);
  45873. },
  45874. enumerable: true,
  45875. configurable: true
  45876. });
  45877. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45878. /**
  45879. * Gets the shadow projection clipping minimum z value.
  45880. */
  45881. get: function () {
  45882. return this._shadowMinZ;
  45883. },
  45884. /**
  45885. * Sets the shadow projection clipping minimum z value.
  45886. */
  45887. set: function (value) {
  45888. this._shadowMinZ = value;
  45889. this.forceProjectionMatrixCompute();
  45890. },
  45891. enumerable: true,
  45892. configurable: true
  45893. });
  45894. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45895. /**
  45896. * Sets the shadow projection clipping maximum z value.
  45897. */
  45898. get: function () {
  45899. return this._shadowMaxZ;
  45900. },
  45901. /**
  45902. * Gets the shadow projection clipping maximum z value.
  45903. */
  45904. set: function (value) {
  45905. this._shadowMaxZ = value;
  45906. this.forceProjectionMatrixCompute();
  45907. },
  45908. enumerable: true,
  45909. configurable: true
  45910. });
  45911. /**
  45912. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45913. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45914. */
  45915. ShadowLight.prototype.computeTransformedInformation = function () {
  45916. if (this.parent && this.parent.getWorldMatrix) {
  45917. if (!this.transformedPosition) {
  45918. this.transformedPosition = BABYLON.Vector3.Zero();
  45919. }
  45920. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45921. // In case the direction is present.
  45922. if (this.direction) {
  45923. if (!this.transformedDirection) {
  45924. this.transformedDirection = BABYLON.Vector3.Zero();
  45925. }
  45926. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45927. }
  45928. return true;
  45929. }
  45930. return false;
  45931. };
  45932. /**
  45933. * Return the depth scale used for the shadow map.
  45934. * @returns the depth scale.
  45935. */
  45936. ShadowLight.prototype.getDepthScale = function () {
  45937. return 50.0;
  45938. };
  45939. /**
  45940. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  45941. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45942. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45943. */
  45944. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  45945. return this.transformedDirection ? this.transformedDirection : this.direction;
  45946. };
  45947. /**
  45948. * Returns the ShadowLight absolute position in the World.
  45949. * @returns the position vector in world space
  45950. */
  45951. ShadowLight.prototype.getAbsolutePosition = function () {
  45952. return this.transformedPosition ? this.transformedPosition : this.position;
  45953. };
  45954. /**
  45955. * Sets the ShadowLight direction toward the passed target.
  45956. * @param target The point tot target in local space
  45957. * @returns the updated ShadowLight direction
  45958. */
  45959. ShadowLight.prototype.setDirectionToTarget = function (target) {
  45960. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  45961. return this.direction;
  45962. };
  45963. /**
  45964. * Returns the light rotation in euler definition.
  45965. * @returns the x y z rotation in local space.
  45966. */
  45967. ShadowLight.prototype.getRotation = function () {
  45968. this.direction.normalize();
  45969. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  45970. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  45971. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  45972. };
  45973. /**
  45974. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  45975. * @returns true if a cube texture needs to be use
  45976. */
  45977. ShadowLight.prototype.needCube = function () {
  45978. return false;
  45979. };
  45980. /**
  45981. * Detects if the projection matrix requires to be recomputed this frame.
  45982. * @returns true if it requires to be recomputed otherwise, false.
  45983. */
  45984. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  45985. return this._needProjectionMatrixCompute;
  45986. };
  45987. /**
  45988. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  45989. */
  45990. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  45991. this._needProjectionMatrixCompute = true;
  45992. };
  45993. /**
  45994. * Get the world matrix of the sahdow lights.
  45995. * @ignore Internal Use Only
  45996. */
  45997. ShadowLight.prototype._getWorldMatrix = function () {
  45998. if (!this._worldMatrix) {
  45999. this._worldMatrix = BABYLON.Matrix.Identity();
  46000. }
  46001. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  46002. return this._worldMatrix;
  46003. };
  46004. /**
  46005. * Gets the minZ used for shadow according to both the scene and the light.
  46006. * @param activeCamera The camera we are returning the min for
  46007. * @returns the depth min z
  46008. */
  46009. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  46010. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  46011. };
  46012. /**
  46013. * Gets the maxZ used for shadow according to both the scene and the light.
  46014. * @param activeCamera The camera we are returning the max for
  46015. * @returns the depth max z
  46016. */
  46017. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  46018. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  46019. };
  46020. /**
  46021. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  46022. * @param matrix The materix to updated with the projection information
  46023. * @param viewMatrix The transform matrix of the light
  46024. * @param renderList The list of mesh to render in the map
  46025. * @returns The current light
  46026. */
  46027. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46028. if (this.customProjectionMatrixBuilder) {
  46029. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  46030. }
  46031. else {
  46032. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46033. }
  46034. return this;
  46035. };
  46036. __decorate([
  46037. BABYLON.serializeAsVector3()
  46038. ], ShadowLight.prototype, "position", null);
  46039. __decorate([
  46040. BABYLON.serializeAsVector3()
  46041. ], ShadowLight.prototype, "direction", null);
  46042. __decorate([
  46043. BABYLON.serialize()
  46044. ], ShadowLight.prototype, "shadowMinZ", null);
  46045. __decorate([
  46046. BABYLON.serialize()
  46047. ], ShadowLight.prototype, "shadowMaxZ", null);
  46048. return ShadowLight;
  46049. }(BABYLON.Light));
  46050. BABYLON.ShadowLight = ShadowLight;
  46051. })(BABYLON || (BABYLON = {}));
  46052. //# sourceMappingURL=babylon.shadowLight.js.map
  46053. "use strict";
  46054. var BABYLON;
  46055. (function (BABYLON) {
  46056. /**
  46057. * A point light is a light defined by an unique point in world space.
  46058. * The light is emitted in every direction from this point.
  46059. * A good example of a point light is a standard light bulb.
  46060. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46061. */
  46062. var PointLight = /** @class */ (function (_super) {
  46063. __extends(PointLight, _super);
  46064. /**
  46065. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  46066. * A PointLight emits the light in every direction.
  46067. * It can cast shadows.
  46068. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  46069. * ```javascript
  46070. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  46071. * ```
  46072. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46073. * @param name The light friendly name
  46074. * @param position The position of the point light in the scene
  46075. * @param scene The scene the lights belongs to
  46076. */
  46077. function PointLight(name, position, scene) {
  46078. var _this = _super.call(this, name, scene) || this;
  46079. _this._shadowAngle = Math.PI / 2;
  46080. _this.position = position;
  46081. return _this;
  46082. }
  46083. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  46084. /**
  46085. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46086. * This specifies what angle the shadow will use to be created.
  46087. *
  46088. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46089. */
  46090. get: function () {
  46091. return this._shadowAngle;
  46092. },
  46093. /**
  46094. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46095. * This specifies what angle the shadow will use to be created.
  46096. *
  46097. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46098. */
  46099. set: function (value) {
  46100. this._shadowAngle = value;
  46101. this.forceProjectionMatrixCompute();
  46102. },
  46103. enumerable: true,
  46104. configurable: true
  46105. });
  46106. Object.defineProperty(PointLight.prototype, "direction", {
  46107. /**
  46108. * Gets the direction if it has been set.
  46109. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46110. */
  46111. get: function () {
  46112. return this._direction;
  46113. },
  46114. /**
  46115. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46116. */
  46117. set: function (value) {
  46118. var previousNeedCube = this.needCube();
  46119. this._direction = value;
  46120. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  46121. this._shadowGenerator.recreateShadowMap();
  46122. }
  46123. },
  46124. enumerable: true,
  46125. configurable: true
  46126. });
  46127. /**
  46128. * Returns the string "PointLight"
  46129. * @returns the class name
  46130. */
  46131. PointLight.prototype.getClassName = function () {
  46132. return "PointLight";
  46133. };
  46134. /**
  46135. * Returns the integer 0.
  46136. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46137. */
  46138. PointLight.prototype.getTypeID = function () {
  46139. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  46140. };
  46141. /**
  46142. * Specifies wether or not the shadowmap should be a cube texture.
  46143. * @returns true if the shadowmap needs to be a cube texture.
  46144. */
  46145. PointLight.prototype.needCube = function () {
  46146. return !this.direction;
  46147. };
  46148. /**
  46149. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  46150. * @param faceIndex The index of the face we are computed the direction to generate shadow
  46151. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  46152. */
  46153. PointLight.prototype.getShadowDirection = function (faceIndex) {
  46154. if (this.direction) {
  46155. return _super.prototype.getShadowDirection.call(this, faceIndex);
  46156. }
  46157. else {
  46158. switch (faceIndex) {
  46159. case 0:
  46160. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  46161. case 1:
  46162. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  46163. case 2:
  46164. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  46165. case 3:
  46166. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  46167. case 4:
  46168. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  46169. case 5:
  46170. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  46171. }
  46172. }
  46173. return BABYLON.Vector3.Zero();
  46174. };
  46175. /**
  46176. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  46177. * - fov = PI / 2
  46178. * - aspect ratio : 1.0
  46179. * - z-near and far equal to the active camera minZ and maxZ.
  46180. * Returns the PointLight.
  46181. */
  46182. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46183. var activeCamera = this.getScene().activeCamera;
  46184. if (!activeCamera) {
  46185. return;
  46186. }
  46187. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46188. };
  46189. PointLight.prototype._buildUniformLayout = function () {
  46190. this._uniformBuffer.addUniform("vLightData", 4);
  46191. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46192. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46193. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46194. this._uniformBuffer.addUniform("depthValues", 2);
  46195. this._uniformBuffer.create();
  46196. };
  46197. /**
  46198. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  46199. * @param effect The effect to update
  46200. * @param lightIndex The index of the light in the effect to update
  46201. * @returns The point light
  46202. */
  46203. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  46204. if (this.computeTransformedInformation()) {
  46205. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  46206. return this;
  46207. }
  46208. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  46209. return this;
  46210. };
  46211. __decorate([
  46212. BABYLON.serialize()
  46213. ], PointLight.prototype, "shadowAngle", null);
  46214. return PointLight;
  46215. }(BABYLON.ShadowLight));
  46216. BABYLON.PointLight = PointLight;
  46217. })(BABYLON || (BABYLON = {}));
  46218. //# sourceMappingURL=babylon.pointLight.js.map
  46219. "use strict";
  46220. var BABYLON;
  46221. (function (BABYLON) {
  46222. /**
  46223. * A directional light is defined by a direction (what a surprise!).
  46224. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  46225. * 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.
  46226. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46227. */
  46228. var DirectionalLight = /** @class */ (function (_super) {
  46229. __extends(DirectionalLight, _super);
  46230. /**
  46231. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  46232. * The directional light is emitted from everywhere in the given direction.
  46233. * It can cast shawdows.
  46234. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46235. * @param name The friendly name of the light
  46236. * @param direction The direction of the light
  46237. * @param scene The scene the light belongs to
  46238. */
  46239. function DirectionalLight(name, direction, scene) {
  46240. var _this = _super.call(this, name, scene) || this;
  46241. _this._shadowFrustumSize = 0;
  46242. _this._shadowOrthoScale = 0.1;
  46243. /**
  46244. * Automatically compute the projection matrix to best fit (including all the casters)
  46245. * on each frame.
  46246. */
  46247. _this.autoUpdateExtends = true;
  46248. // Cache
  46249. _this._orthoLeft = Number.MAX_VALUE;
  46250. _this._orthoRight = Number.MIN_VALUE;
  46251. _this._orthoTop = Number.MIN_VALUE;
  46252. _this._orthoBottom = Number.MAX_VALUE;
  46253. _this.position = direction.scale(-1.0);
  46254. _this.direction = direction;
  46255. return _this;
  46256. }
  46257. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  46258. /**
  46259. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  46260. */
  46261. get: function () {
  46262. return this._shadowFrustumSize;
  46263. },
  46264. /**
  46265. * Specifies a fix frustum size for the shadow generation.
  46266. */
  46267. set: function (value) {
  46268. this._shadowFrustumSize = value;
  46269. this.forceProjectionMatrixCompute();
  46270. },
  46271. enumerable: true,
  46272. configurable: true
  46273. });
  46274. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  46275. /**
  46276. * Gets the shadow projection scale against the optimal computed one.
  46277. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46278. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46279. */
  46280. get: function () {
  46281. return this._shadowOrthoScale;
  46282. },
  46283. /**
  46284. * Sets the shadow projection scale against the optimal computed one.
  46285. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46286. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46287. */
  46288. set: function (value) {
  46289. this._shadowOrthoScale = value;
  46290. this.forceProjectionMatrixCompute();
  46291. },
  46292. enumerable: true,
  46293. configurable: true
  46294. });
  46295. /**
  46296. * Returns the string "DirectionalLight".
  46297. * @return The class name
  46298. */
  46299. DirectionalLight.prototype.getClassName = function () {
  46300. return "DirectionalLight";
  46301. };
  46302. /**
  46303. * Returns the integer 1.
  46304. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46305. */
  46306. DirectionalLight.prototype.getTypeID = function () {
  46307. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  46308. };
  46309. /**
  46310. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  46311. * Returns the DirectionalLight Shadow projection matrix.
  46312. */
  46313. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46314. if (this.shadowFrustumSize > 0) {
  46315. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  46316. }
  46317. else {
  46318. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46319. }
  46320. };
  46321. /**
  46322. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  46323. * Returns the DirectionalLight Shadow projection matrix.
  46324. */
  46325. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  46326. var activeCamera = this.getScene().activeCamera;
  46327. if (!activeCamera) {
  46328. return;
  46329. }
  46330. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  46331. };
  46332. /**
  46333. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  46334. * Returns the DirectionalLight Shadow projection matrix.
  46335. */
  46336. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46337. var activeCamera = this.getScene().activeCamera;
  46338. if (!activeCamera) {
  46339. return;
  46340. }
  46341. // Check extends
  46342. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  46343. var tempVector3 = BABYLON.Vector3.Zero();
  46344. this._orthoLeft = Number.MAX_VALUE;
  46345. this._orthoRight = Number.MIN_VALUE;
  46346. this._orthoTop = Number.MIN_VALUE;
  46347. this._orthoBottom = Number.MAX_VALUE;
  46348. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  46349. var mesh = renderList[meshIndex];
  46350. if (!mesh) {
  46351. continue;
  46352. }
  46353. var boundingInfo = mesh.getBoundingInfo();
  46354. var boundingBox = boundingInfo.boundingBox;
  46355. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  46356. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  46357. if (tempVector3.x < this._orthoLeft)
  46358. this._orthoLeft = tempVector3.x;
  46359. if (tempVector3.y < this._orthoBottom)
  46360. this._orthoBottom = tempVector3.y;
  46361. if (tempVector3.x > this._orthoRight)
  46362. this._orthoRight = tempVector3.x;
  46363. if (tempVector3.y > this._orthoTop)
  46364. this._orthoTop = tempVector3.y;
  46365. }
  46366. }
  46367. }
  46368. var xOffset = this._orthoRight - this._orthoLeft;
  46369. var yOffset = this._orthoTop - this._orthoBottom;
  46370. 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);
  46371. };
  46372. DirectionalLight.prototype._buildUniformLayout = function () {
  46373. this._uniformBuffer.addUniform("vLightData", 4);
  46374. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46375. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46376. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46377. this._uniformBuffer.addUniform("depthValues", 2);
  46378. this._uniformBuffer.create();
  46379. };
  46380. /**
  46381. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  46382. * @param effect The effect to update
  46383. * @param lightIndex The index of the light in the effect to update
  46384. * @returns The directional light
  46385. */
  46386. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  46387. if (this.computeTransformedInformation()) {
  46388. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  46389. return this;
  46390. }
  46391. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  46392. return this;
  46393. };
  46394. /**
  46395. * Gets the minZ used for shadow according to both the scene and the light.
  46396. *
  46397. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46398. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46399. * @param activeCamera The camera we are returning the min for
  46400. * @returns the depth min z
  46401. */
  46402. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  46403. return 1;
  46404. };
  46405. /**
  46406. * Gets the maxZ used for shadow according to both the scene and the light.
  46407. *
  46408. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46409. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46410. * @param activeCamera The camera we are returning the max for
  46411. * @returns the depth max z
  46412. */
  46413. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  46414. return 1;
  46415. };
  46416. __decorate([
  46417. BABYLON.serialize()
  46418. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  46419. __decorate([
  46420. BABYLON.serialize()
  46421. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  46422. __decorate([
  46423. BABYLON.serialize()
  46424. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  46425. return DirectionalLight;
  46426. }(BABYLON.ShadowLight));
  46427. BABYLON.DirectionalLight = DirectionalLight;
  46428. })(BABYLON || (BABYLON = {}));
  46429. //# sourceMappingURL=babylon.directionalLight.js.map
  46430. "use strict";
  46431. var BABYLON;
  46432. (function (BABYLON) {
  46433. /**
  46434. * A spot light is defined by a position, a direction, an angle, and an exponent.
  46435. * These values define a cone of light starting from the position, emitting toward the direction.
  46436. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  46437. * and the exponent defines the speed of the decay of the light with distance (reach).
  46438. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46439. */
  46440. var SpotLight = /** @class */ (function (_super) {
  46441. __extends(SpotLight, _super);
  46442. /**
  46443. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  46444. * It can cast shadows.
  46445. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46446. * @param name The light friendly name
  46447. * @param position The position of the spot light in the scene
  46448. * @param direction The direction of the light in the scene
  46449. * @param angle The cone angle of the light in Radians
  46450. * @param exponent The light decay speed with the distance from the emission spot
  46451. * @param scene The scene the lights belongs to
  46452. */
  46453. function SpotLight(name, position, direction, angle, exponent, scene) {
  46454. var _this = _super.call(this, name, scene) || this;
  46455. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  46456. _this._projectionTextureLightNear = 1e-6;
  46457. _this._projectionTextureLightFar = 1000.0;
  46458. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  46459. _this._projectionTextureViewLightDirty = true;
  46460. _this._projectionTextureProjectionLightDirty = true;
  46461. _this._projectionTextureDirty = true;
  46462. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  46463. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  46464. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  46465. _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);
  46466. _this.position = position;
  46467. _this.direction = direction;
  46468. _this.angle = angle;
  46469. _this.exponent = exponent;
  46470. return _this;
  46471. }
  46472. Object.defineProperty(SpotLight.prototype, "angle", {
  46473. /**
  46474. * Gets the cone angle of the spot light in Radians.
  46475. */
  46476. get: function () {
  46477. return this._angle;
  46478. },
  46479. /**
  46480. * Sets the cone angle of the spot light in Radians.
  46481. */
  46482. set: function (value) {
  46483. this._angle = value;
  46484. this._projectionTextureProjectionLightDirty = true;
  46485. this.forceProjectionMatrixCompute();
  46486. },
  46487. enumerable: true,
  46488. configurable: true
  46489. });
  46490. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  46491. /**
  46492. * Allows scaling the angle of the light for shadow generation only.
  46493. */
  46494. get: function () {
  46495. return this._shadowAngleScale;
  46496. },
  46497. /**
  46498. * Allows scaling the angle of the light for shadow generation only.
  46499. */
  46500. set: function (value) {
  46501. this._shadowAngleScale = value;
  46502. this.forceProjectionMatrixCompute();
  46503. },
  46504. enumerable: true,
  46505. configurable: true
  46506. });
  46507. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  46508. /**
  46509. * Allows reading the projecton texture
  46510. */
  46511. get: function () {
  46512. return this._projectionTextureMatrix;
  46513. },
  46514. enumerable: true,
  46515. configurable: true
  46516. });
  46517. ;
  46518. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  46519. /**
  46520. * Gets the near clip of the Spotlight for texture projection.
  46521. */
  46522. get: function () {
  46523. return this._projectionTextureLightNear;
  46524. },
  46525. /**
  46526. * Sets the near clip of the Spotlight for texture projection.
  46527. */
  46528. set: function (value) {
  46529. this._projectionTextureLightNear = value;
  46530. this._projectionTextureProjectionLightDirty = true;
  46531. },
  46532. enumerable: true,
  46533. configurable: true
  46534. });
  46535. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  46536. /**
  46537. * Gets the far clip of the Spotlight for texture projection.
  46538. */
  46539. get: function () {
  46540. return this._projectionTextureLightFar;
  46541. },
  46542. /**
  46543. * Sets the far clip of the Spotlight for texture projection.
  46544. */
  46545. set: function (value) {
  46546. this._projectionTextureLightFar = value;
  46547. this._projectionTextureProjectionLightDirty = true;
  46548. },
  46549. enumerable: true,
  46550. configurable: true
  46551. });
  46552. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  46553. /**
  46554. * Gets the Up vector of the Spotlight for texture projection.
  46555. */
  46556. get: function () {
  46557. return this._projectionTextureUpDirection;
  46558. },
  46559. /**
  46560. * Sets the Up vector of the Spotlight for texture projection.
  46561. */
  46562. set: function (value) {
  46563. this._projectionTextureUpDirection = value;
  46564. this._projectionTextureProjectionLightDirty = true;
  46565. },
  46566. enumerable: true,
  46567. configurable: true
  46568. });
  46569. ;
  46570. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  46571. /**
  46572. * Gets the projection texture of the light.
  46573. */
  46574. get: function () {
  46575. return this._projectionTexture;
  46576. },
  46577. /**
  46578. * Sets the projection texture of the light.
  46579. */
  46580. set: function (value) {
  46581. this._projectionTexture = value;
  46582. this._projectionTextureDirty = true;
  46583. },
  46584. enumerable: true,
  46585. configurable: true
  46586. });
  46587. /**
  46588. * Returns the string "SpotLight".
  46589. * @returns the class name
  46590. */
  46591. SpotLight.prototype.getClassName = function () {
  46592. return "SpotLight";
  46593. };
  46594. /**
  46595. * Returns the integer 2.
  46596. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46597. */
  46598. SpotLight.prototype.getTypeID = function () {
  46599. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  46600. };
  46601. /**
  46602. * Overrides the direction setter to recompute the projection texture view light Matrix.
  46603. */
  46604. SpotLight.prototype._setDirection = function (value) {
  46605. _super.prototype._setDirection.call(this, value);
  46606. this._projectionTextureViewLightDirty = true;
  46607. };
  46608. /**
  46609. * Overrides the position setter to recompute the projection texture view light Matrix.
  46610. */
  46611. SpotLight.prototype._setPosition = function (value) {
  46612. _super.prototype._setPosition.call(this, value);
  46613. this._projectionTextureViewLightDirty = true;
  46614. };
  46615. /**
  46616. * 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.
  46617. * Returns the SpotLight.
  46618. */
  46619. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46620. var activeCamera = this.getScene().activeCamera;
  46621. if (!activeCamera) {
  46622. return;
  46623. }
  46624. this._shadowAngleScale = this._shadowAngleScale || 1;
  46625. var angle = this._shadowAngleScale * this._angle;
  46626. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46627. };
  46628. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  46629. this._projectionTextureViewLightDirty = false;
  46630. this._projectionTextureDirty = true;
  46631. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  46632. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  46633. };
  46634. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  46635. this._projectionTextureProjectionLightDirty = false;
  46636. this._projectionTextureDirty = true;
  46637. var light_far = this.projectionTextureLightFar;
  46638. var light_near = this.projectionTextureLightNear;
  46639. var P = light_far / (light_far - light_near);
  46640. var Q = -P * light_near;
  46641. var S = 1.0 / Math.tan(this._angle / 2.0);
  46642. var A = 1.0;
  46643. 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);
  46644. };
  46645. /**
  46646. * Main function for light texture projection matrix computing.
  46647. */
  46648. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  46649. this._projectionTextureDirty = false;
  46650. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46651. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46652. };
  46653. SpotLight.prototype._buildUniformLayout = function () {
  46654. this._uniformBuffer.addUniform("vLightData", 4);
  46655. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46656. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46657. this._uniformBuffer.addUniform("vLightDirection", 3);
  46658. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46659. this._uniformBuffer.addUniform("depthValues", 2);
  46660. this._uniformBuffer.create();
  46661. };
  46662. /**
  46663. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46664. * @param effect The effect to update
  46665. * @param lightIndex The index of the light in the effect to update
  46666. * @returns The spot light
  46667. */
  46668. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46669. var normalizeDirection;
  46670. if (this.computeTransformedInformation()) {
  46671. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46672. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46673. }
  46674. else {
  46675. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46676. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46677. }
  46678. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46679. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46680. if (this._projectionTextureViewLightDirty) {
  46681. this._computeProjectionTextureViewLightMatrix();
  46682. }
  46683. if (this._projectionTextureProjectionLightDirty) {
  46684. this._computeProjectionTextureProjectionLightMatrix();
  46685. }
  46686. if (this._projectionTextureDirty) {
  46687. this._computeProjectionTextureMatrix();
  46688. }
  46689. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46690. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46691. }
  46692. return this;
  46693. };
  46694. /**
  46695. * Disposes the light and the associated resources.
  46696. */
  46697. SpotLight.prototype.dispose = function () {
  46698. _super.prototype.dispose.call(this);
  46699. if (this._projectionTexture) {
  46700. this._projectionTexture.dispose();
  46701. }
  46702. };
  46703. __decorate([
  46704. BABYLON.serialize()
  46705. ], SpotLight.prototype, "angle", null);
  46706. __decorate([
  46707. BABYLON.serialize()
  46708. ], SpotLight.prototype, "shadowAngleScale", null);
  46709. __decorate([
  46710. BABYLON.serialize()
  46711. ], SpotLight.prototype, "exponent", void 0);
  46712. __decorate([
  46713. BABYLON.serialize()
  46714. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46715. __decorate([
  46716. BABYLON.serialize()
  46717. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46718. __decorate([
  46719. BABYLON.serialize()
  46720. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46721. __decorate([
  46722. BABYLON.serializeAsTexture("projectedLightTexture")
  46723. ], SpotLight.prototype, "_projectionTexture", void 0);
  46724. return SpotLight;
  46725. }(BABYLON.ShadowLight));
  46726. BABYLON.SpotLight = SpotLight;
  46727. })(BABYLON || (BABYLON = {}));
  46728. //# sourceMappingURL=babylon.spotLight.js.map
  46729. "use strict";
  46730. var BABYLON;
  46731. (function (BABYLON) {
  46732. /**
  46733. * Class used to override all child animations of a given target
  46734. */
  46735. var AnimationPropertiesOverride = /** @class */ (function () {
  46736. function AnimationPropertiesOverride() {
  46737. /**
  46738. * Gets or sets a value indicating if animation blending must be used
  46739. */
  46740. this.enableBlending = false;
  46741. /**
  46742. * Gets or sets the blending speed to use when enableBlending is true
  46743. */
  46744. this.blendingSpeed = 0.01;
  46745. /**
  46746. * Gets or sets the default loop mode to use
  46747. */
  46748. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46749. }
  46750. return AnimationPropertiesOverride;
  46751. }());
  46752. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46753. })(BABYLON || (BABYLON = {}));
  46754. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46755. "use strict";
  46756. var BABYLON;
  46757. (function (BABYLON) {
  46758. var AnimationRange = /** @class */ (function () {
  46759. function AnimationRange(name, from, to) {
  46760. this.name = name;
  46761. this.from = from;
  46762. this.to = to;
  46763. }
  46764. AnimationRange.prototype.clone = function () {
  46765. return new AnimationRange(this.name, this.from, this.to);
  46766. };
  46767. return AnimationRange;
  46768. }());
  46769. BABYLON.AnimationRange = AnimationRange;
  46770. /**
  46771. * Composed of a frame, and an action function
  46772. */
  46773. var AnimationEvent = /** @class */ (function () {
  46774. function AnimationEvent(frame, action, onlyOnce) {
  46775. this.frame = frame;
  46776. this.action = action;
  46777. this.onlyOnce = onlyOnce;
  46778. this.isDone = false;
  46779. }
  46780. return AnimationEvent;
  46781. }());
  46782. BABYLON.AnimationEvent = AnimationEvent;
  46783. var PathCursor = /** @class */ (function () {
  46784. function PathCursor(path) {
  46785. this.path = path;
  46786. this._onchange = new Array();
  46787. this.value = 0;
  46788. this.animations = new Array();
  46789. }
  46790. PathCursor.prototype.getPoint = function () {
  46791. var point = this.path.getPointAtLengthPosition(this.value);
  46792. return new BABYLON.Vector3(point.x, 0, point.y);
  46793. };
  46794. PathCursor.prototype.moveAhead = function (step) {
  46795. if (step === void 0) { step = 0.002; }
  46796. this.move(step);
  46797. return this;
  46798. };
  46799. PathCursor.prototype.moveBack = function (step) {
  46800. if (step === void 0) { step = 0.002; }
  46801. this.move(-step);
  46802. return this;
  46803. };
  46804. PathCursor.prototype.move = function (step) {
  46805. if (Math.abs(step) > 1) {
  46806. throw "step size should be less than 1.";
  46807. }
  46808. this.value += step;
  46809. this.ensureLimits();
  46810. this.raiseOnChange();
  46811. return this;
  46812. };
  46813. PathCursor.prototype.ensureLimits = function () {
  46814. while (this.value > 1) {
  46815. this.value -= 1;
  46816. }
  46817. while (this.value < 0) {
  46818. this.value += 1;
  46819. }
  46820. return this;
  46821. };
  46822. // used by animation engine
  46823. PathCursor.prototype.raiseOnChange = function () {
  46824. var _this = this;
  46825. this._onchange.forEach(function (f) { return f(_this); });
  46826. return this;
  46827. };
  46828. PathCursor.prototype.onchange = function (f) {
  46829. this._onchange.push(f);
  46830. return this;
  46831. };
  46832. return PathCursor;
  46833. }());
  46834. BABYLON.PathCursor = PathCursor;
  46835. var AnimationKeyInterpolation;
  46836. (function (AnimationKeyInterpolation) {
  46837. /**
  46838. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46839. */
  46840. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46841. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46842. var Animation = /** @class */ (function () {
  46843. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46844. this.name = name;
  46845. this.targetProperty = targetProperty;
  46846. this.framePerSecond = framePerSecond;
  46847. this.dataType = dataType;
  46848. this.loopMode = loopMode;
  46849. this.enableBlending = enableBlending;
  46850. this._runtimeAnimations = new Array();
  46851. // The set of event that will be linked to this animation
  46852. this._events = new Array();
  46853. this.blendingSpeed = 0.01;
  46854. this._ranges = {};
  46855. this.targetPropertyPath = targetProperty.split(".");
  46856. this.dataType = dataType;
  46857. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46858. }
  46859. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46860. var dataType = undefined;
  46861. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46862. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46863. }
  46864. else if (from instanceof BABYLON.Quaternion) {
  46865. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46866. }
  46867. else if (from instanceof BABYLON.Vector3) {
  46868. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46869. }
  46870. else if (from instanceof BABYLON.Vector2) {
  46871. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46872. }
  46873. else if (from instanceof BABYLON.Color3) {
  46874. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46875. }
  46876. else if (from instanceof BABYLON.Size) {
  46877. dataType = Animation.ANIMATIONTYPE_SIZE;
  46878. }
  46879. if (dataType == undefined) {
  46880. return null;
  46881. }
  46882. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46883. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46884. animation.setKeys(keys);
  46885. if (easingFunction !== undefined) {
  46886. animation.setEasingFunction(easingFunction);
  46887. }
  46888. return animation;
  46889. };
  46890. /**
  46891. * Sets up an animation.
  46892. * @param property the property to animate
  46893. * @param animationType the animation type to apply
  46894. * @param easingFunction the easing function used in the animation
  46895. * @returns The created animation
  46896. */
  46897. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46898. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46899. animation.setEasingFunction(easingFunction);
  46900. return animation;
  46901. };
  46902. /**
  46903. * Create and start an animation on a node
  46904. * @param {string} name defines the name of the global animation that will be run on all nodes
  46905. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46906. * @param {string} targetProperty defines property to animate
  46907. * @param {number} framePerSecond defines the number of frame per second yo use
  46908. * @param {number} totalFrame defines the number of frames in total
  46909. * @param {any} from defines the initial value
  46910. * @param {any} to defines the final value
  46911. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46912. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46913. * @param onAnimationEnd defines the callback to call when animation end
  46914. * @returns the animatable created for this animation
  46915. */
  46916. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46917. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46918. if (!animation) {
  46919. return null;
  46920. }
  46921. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46922. };
  46923. /**
  46924. * Create and start an animation on a node and its descendants
  46925. * @param {string} name defines the name of the global animation that will be run on all nodes
  46926. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46927. * @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.
  46928. * @param {string} targetProperty defines property to animate
  46929. * @param {number} framePerSecond defines the number of frame per second yo use
  46930. * @param {number} totalFrame defines the number of frames in total
  46931. * @param {any} from defines the initial value
  46932. * @param {any} to defines the final value
  46933. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46934. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46935. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  46936. * @returns the list of animatables created for all nodes
  46937. * @example https://www.babylonjs-playground.com/#MH0VLI
  46938. */
  46939. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46940. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46941. if (!animation) {
  46942. return null;
  46943. }
  46944. var scene = node.getScene();
  46945. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46946. };
  46947. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46948. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46949. if (!animation) {
  46950. return null;
  46951. }
  46952. node.animations.push(animation);
  46953. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46954. };
  46955. /**
  46956. * Transition property of the Camera to the target Value.
  46957. * @param property The property to transition
  46958. * @param targetValue The target Value of the property
  46959. * @param host The object where the property to animate belongs
  46960. * @param scene Scene used to run the animation
  46961. * @param frameRate Framerate (in frame/s) to use
  46962. * @param transition The transition type we want to use
  46963. * @param duration The duration of the animation, in milliseconds
  46964. * @param onAnimationEnd Call back trigger at the end of the animation.
  46965. */
  46966. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  46967. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  46968. if (duration <= 0) {
  46969. host[property] = targetValue;
  46970. if (onAnimationEnd) {
  46971. onAnimationEnd();
  46972. }
  46973. return null;
  46974. }
  46975. var endFrame = frameRate * (duration / 1000);
  46976. transition.setKeys([{
  46977. frame: 0,
  46978. value: host[property].clone ? host[property].clone() : host[property]
  46979. },
  46980. {
  46981. frame: endFrame,
  46982. value: targetValue
  46983. }]);
  46984. if (!host.animations) {
  46985. host.animations = [];
  46986. }
  46987. host.animations.push(transition);
  46988. var animation = scene.beginAnimation(host, 0, endFrame, false);
  46989. animation.onAnimationEnd = onAnimationEnd;
  46990. return animation;
  46991. };
  46992. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  46993. /**
  46994. * Return the array of runtime animations currently using this animation
  46995. */
  46996. get: function () {
  46997. return this._runtimeAnimations;
  46998. },
  46999. enumerable: true,
  47000. configurable: true
  47001. });
  47002. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  47003. get: function () {
  47004. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  47005. var runtimeAnimation = _a[_i];
  47006. if (!runtimeAnimation.isStopped) {
  47007. return true;
  47008. }
  47009. }
  47010. return false;
  47011. },
  47012. enumerable: true,
  47013. configurable: true
  47014. });
  47015. // Methods
  47016. /**
  47017. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  47018. */
  47019. Animation.prototype.toString = function (fullDetails) {
  47020. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  47021. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  47022. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  47023. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  47024. if (fullDetails) {
  47025. ret += ", Ranges: {";
  47026. var first = true;
  47027. for (var name in this._ranges) {
  47028. if (first) {
  47029. ret += ", ";
  47030. first = false;
  47031. }
  47032. ret += name;
  47033. }
  47034. ret += "}";
  47035. }
  47036. return ret;
  47037. };
  47038. /**
  47039. * Add an event to this animation.
  47040. */
  47041. Animation.prototype.addEvent = function (event) {
  47042. this._events.push(event);
  47043. };
  47044. /**
  47045. * Remove all events found at the given frame
  47046. * @param frame
  47047. */
  47048. Animation.prototype.removeEvents = function (frame) {
  47049. for (var index = 0; index < this._events.length; index++) {
  47050. if (this._events[index].frame === frame) {
  47051. this._events.splice(index, 1);
  47052. index--;
  47053. }
  47054. }
  47055. };
  47056. Animation.prototype.getEvents = function () {
  47057. return this._events;
  47058. };
  47059. Animation.prototype.createRange = function (name, from, to) {
  47060. // check name not already in use; could happen for bones after serialized
  47061. if (!this._ranges[name]) {
  47062. this._ranges[name] = new AnimationRange(name, from, to);
  47063. }
  47064. };
  47065. Animation.prototype.deleteRange = function (name, deleteFrames) {
  47066. if (deleteFrames === void 0) { deleteFrames = true; }
  47067. var range = this._ranges[name];
  47068. if (!range) {
  47069. return;
  47070. }
  47071. if (deleteFrames) {
  47072. var from = range.from;
  47073. var to = range.to;
  47074. // this loop MUST go high to low for multiple splices to work
  47075. for (var key = this._keys.length - 1; key >= 0; key--) {
  47076. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  47077. this._keys.splice(key, 1);
  47078. }
  47079. }
  47080. }
  47081. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  47082. };
  47083. Animation.prototype.getRange = function (name) {
  47084. return this._ranges[name];
  47085. };
  47086. Animation.prototype.getKeys = function () {
  47087. return this._keys;
  47088. };
  47089. Animation.prototype.getHighestFrame = function () {
  47090. var ret = 0;
  47091. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  47092. if (ret < this._keys[key].frame) {
  47093. ret = this._keys[key].frame;
  47094. }
  47095. }
  47096. return ret;
  47097. };
  47098. Animation.prototype.getEasingFunction = function () {
  47099. return this._easingFunction;
  47100. };
  47101. Animation.prototype.setEasingFunction = function (easingFunction) {
  47102. this._easingFunction = easingFunction;
  47103. };
  47104. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  47105. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  47106. };
  47107. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47108. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47109. };
  47110. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  47111. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  47112. };
  47113. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47114. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  47115. };
  47116. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  47117. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  47118. };
  47119. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47120. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47121. };
  47122. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  47123. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  47124. };
  47125. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47126. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47127. };
  47128. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  47129. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  47130. };
  47131. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  47132. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  47133. };
  47134. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  47135. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  47136. };
  47137. Animation.prototype.clone = function () {
  47138. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  47139. clone.enableBlending = this.enableBlending;
  47140. clone.blendingSpeed = this.blendingSpeed;
  47141. if (this._keys) {
  47142. clone.setKeys(this._keys);
  47143. }
  47144. if (this._ranges) {
  47145. clone._ranges = {};
  47146. for (var name in this._ranges) {
  47147. var range = this._ranges[name];
  47148. if (!range) {
  47149. continue;
  47150. }
  47151. clone._ranges[name] = range.clone();
  47152. }
  47153. }
  47154. return clone;
  47155. };
  47156. Animation.prototype.setKeys = function (values) {
  47157. this._keys = values.slice(0);
  47158. };
  47159. Animation.prototype.serialize = function () {
  47160. var serializationObject = {};
  47161. serializationObject.name = this.name;
  47162. serializationObject.property = this.targetProperty;
  47163. serializationObject.framePerSecond = this.framePerSecond;
  47164. serializationObject.dataType = this.dataType;
  47165. serializationObject.loopBehavior = this.loopMode;
  47166. serializationObject.enableBlending = this.enableBlending;
  47167. serializationObject.blendingSpeed = this.blendingSpeed;
  47168. var dataType = this.dataType;
  47169. serializationObject.keys = [];
  47170. var keys = this.getKeys();
  47171. for (var index = 0; index < keys.length; index++) {
  47172. var animationKey = keys[index];
  47173. var key = {};
  47174. key.frame = animationKey.frame;
  47175. switch (dataType) {
  47176. case Animation.ANIMATIONTYPE_FLOAT:
  47177. key.values = [animationKey.value];
  47178. break;
  47179. case Animation.ANIMATIONTYPE_QUATERNION:
  47180. case Animation.ANIMATIONTYPE_MATRIX:
  47181. case Animation.ANIMATIONTYPE_VECTOR3:
  47182. case Animation.ANIMATIONTYPE_COLOR3:
  47183. key.values = animationKey.value.asArray();
  47184. break;
  47185. }
  47186. serializationObject.keys.push(key);
  47187. }
  47188. serializationObject.ranges = [];
  47189. for (var name in this._ranges) {
  47190. var source = this._ranges[name];
  47191. if (!source) {
  47192. continue;
  47193. }
  47194. var range = {};
  47195. range.name = name;
  47196. range.from = source.from;
  47197. range.to = source.to;
  47198. serializationObject.ranges.push(range);
  47199. }
  47200. return serializationObject;
  47201. };
  47202. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  47203. get: function () {
  47204. return Animation._ANIMATIONTYPE_FLOAT;
  47205. },
  47206. enumerable: true,
  47207. configurable: true
  47208. });
  47209. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  47210. get: function () {
  47211. return Animation._ANIMATIONTYPE_VECTOR3;
  47212. },
  47213. enumerable: true,
  47214. configurable: true
  47215. });
  47216. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  47217. get: function () {
  47218. return Animation._ANIMATIONTYPE_VECTOR2;
  47219. },
  47220. enumerable: true,
  47221. configurable: true
  47222. });
  47223. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  47224. get: function () {
  47225. return Animation._ANIMATIONTYPE_SIZE;
  47226. },
  47227. enumerable: true,
  47228. configurable: true
  47229. });
  47230. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  47231. get: function () {
  47232. return Animation._ANIMATIONTYPE_QUATERNION;
  47233. },
  47234. enumerable: true,
  47235. configurable: true
  47236. });
  47237. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  47238. get: function () {
  47239. return Animation._ANIMATIONTYPE_MATRIX;
  47240. },
  47241. enumerable: true,
  47242. configurable: true
  47243. });
  47244. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  47245. get: function () {
  47246. return Animation._ANIMATIONTYPE_COLOR3;
  47247. },
  47248. enumerable: true,
  47249. configurable: true
  47250. });
  47251. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  47252. get: function () {
  47253. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  47254. },
  47255. enumerable: true,
  47256. configurable: true
  47257. });
  47258. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  47259. get: function () {
  47260. return Animation._ANIMATIONLOOPMODE_CYCLE;
  47261. },
  47262. enumerable: true,
  47263. configurable: true
  47264. });
  47265. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  47266. get: function () {
  47267. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  47268. },
  47269. enumerable: true,
  47270. configurable: true
  47271. });
  47272. Animation.Parse = function (parsedAnimation) {
  47273. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  47274. var dataType = parsedAnimation.dataType;
  47275. var keys = [];
  47276. var data;
  47277. var index;
  47278. if (parsedAnimation.enableBlending) {
  47279. animation.enableBlending = parsedAnimation.enableBlending;
  47280. }
  47281. if (parsedAnimation.blendingSpeed) {
  47282. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  47283. }
  47284. for (index = 0; index < parsedAnimation.keys.length; index++) {
  47285. var key = parsedAnimation.keys[index];
  47286. var inTangent;
  47287. var outTangent;
  47288. switch (dataType) {
  47289. case Animation.ANIMATIONTYPE_FLOAT:
  47290. data = key.values[0];
  47291. if (key.values.length >= 1) {
  47292. inTangent = key.values[1];
  47293. }
  47294. if (key.values.length >= 2) {
  47295. outTangent = key.values[2];
  47296. }
  47297. break;
  47298. case Animation.ANIMATIONTYPE_QUATERNION:
  47299. data = BABYLON.Quaternion.FromArray(key.values);
  47300. if (key.values.length >= 8) {
  47301. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  47302. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  47303. inTangent = _inTangent;
  47304. }
  47305. }
  47306. if (key.values.length >= 12) {
  47307. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  47308. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  47309. outTangent = _outTangent;
  47310. }
  47311. }
  47312. break;
  47313. case Animation.ANIMATIONTYPE_MATRIX:
  47314. data = BABYLON.Matrix.FromArray(key.values);
  47315. break;
  47316. case Animation.ANIMATIONTYPE_COLOR3:
  47317. data = BABYLON.Color3.FromArray(key.values);
  47318. break;
  47319. case Animation.ANIMATIONTYPE_VECTOR3:
  47320. default:
  47321. data = BABYLON.Vector3.FromArray(key.values);
  47322. break;
  47323. }
  47324. var keyData = {};
  47325. keyData.frame = key.frame;
  47326. keyData.value = data;
  47327. if (inTangent != undefined) {
  47328. keyData.inTangent = inTangent;
  47329. }
  47330. if (outTangent != undefined) {
  47331. keyData.outTangent = outTangent;
  47332. }
  47333. keys.push(keyData);
  47334. }
  47335. animation.setKeys(keys);
  47336. if (parsedAnimation.ranges) {
  47337. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  47338. data = parsedAnimation.ranges[index];
  47339. animation.createRange(data.name, data.from, data.to);
  47340. }
  47341. }
  47342. return animation;
  47343. };
  47344. Animation.AppendSerializedAnimations = function (source, destination) {
  47345. if (source.animations) {
  47346. destination.animations = [];
  47347. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  47348. var animation = source.animations[animationIndex];
  47349. destination.animations.push(animation.serialize());
  47350. }
  47351. }
  47352. };
  47353. Animation.AllowMatricesInterpolation = false;
  47354. // Statics
  47355. Animation._ANIMATIONTYPE_FLOAT = 0;
  47356. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  47357. Animation._ANIMATIONTYPE_QUATERNION = 2;
  47358. Animation._ANIMATIONTYPE_MATRIX = 3;
  47359. Animation._ANIMATIONTYPE_COLOR3 = 4;
  47360. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  47361. Animation._ANIMATIONTYPE_SIZE = 6;
  47362. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  47363. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  47364. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  47365. return Animation;
  47366. }());
  47367. BABYLON.Animation = Animation;
  47368. })(BABYLON || (BABYLON = {}));
  47369. //# sourceMappingURL=babylon.animation.js.map
  47370. "use strict";
  47371. var BABYLON;
  47372. (function (BABYLON) {
  47373. /**
  47374. * This class defines the direct association between an animation and a target
  47375. */
  47376. var TargetedAnimation = /** @class */ (function () {
  47377. function TargetedAnimation() {
  47378. }
  47379. return TargetedAnimation;
  47380. }());
  47381. BABYLON.TargetedAnimation = TargetedAnimation;
  47382. /**
  47383. * Use this class to create coordinated animations on multiple targets
  47384. */
  47385. var AnimationGroup = /** @class */ (function () {
  47386. function AnimationGroup(name, scene) {
  47387. if (scene === void 0) { scene = null; }
  47388. this.name = name;
  47389. this._targetedAnimations = new Array();
  47390. this._animatables = new Array();
  47391. this._from = Number.MAX_VALUE;
  47392. this._to = -Number.MAX_VALUE;
  47393. this._speedRatio = 1;
  47394. this.onAnimationEndObservable = new BABYLON.Observable();
  47395. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47396. this._scene.animationGroups.push(this);
  47397. }
  47398. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  47399. /**
  47400. * Define if the animations are started
  47401. */
  47402. get: function () {
  47403. return this._isStarted;
  47404. },
  47405. enumerable: true,
  47406. configurable: true
  47407. });
  47408. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  47409. /**
  47410. * Gets or sets the speed ratio to use for all animations
  47411. */
  47412. get: function () {
  47413. return this._speedRatio;
  47414. },
  47415. /**
  47416. * Gets or sets the speed ratio to use for all animations
  47417. */
  47418. set: function (value) {
  47419. if (this._speedRatio === value) {
  47420. return;
  47421. }
  47422. this._speedRatio = value;
  47423. for (var index = 0; index < this._animatables.length; index++) {
  47424. var animatable = this._animatables[index];
  47425. animatable.speedRatio = this._speedRatio;
  47426. }
  47427. },
  47428. enumerable: true,
  47429. configurable: true
  47430. });
  47431. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  47432. /**
  47433. * Gets the targeted animations for this animation group
  47434. */
  47435. get: function () {
  47436. return this._targetedAnimations;
  47437. },
  47438. enumerable: true,
  47439. configurable: true
  47440. });
  47441. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  47442. /**
  47443. * returning the list of animatables controlled by this animation group.
  47444. */
  47445. get: function () {
  47446. return this._animatables;
  47447. },
  47448. enumerable: true,
  47449. configurable: true
  47450. });
  47451. /**
  47452. * Add an animation (with its target) in the group
  47453. * @param animation defines the animation we want to add
  47454. * @param target defines the target of the animation
  47455. * @returns the {BABYLON.TargetedAnimation} object
  47456. */
  47457. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  47458. var targetedAnimation = {
  47459. animation: animation,
  47460. target: target
  47461. };
  47462. var keys = animation.getKeys();
  47463. if (this._from > keys[0].frame) {
  47464. this._from = keys[0].frame;
  47465. }
  47466. if (this._to < keys[keys.length - 1].frame) {
  47467. this._to = keys[keys.length - 1].frame;
  47468. }
  47469. this._targetedAnimations.push(targetedAnimation);
  47470. return targetedAnimation;
  47471. };
  47472. /**
  47473. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  47474. * It can add constant keys at begin or end
  47475. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  47476. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  47477. */
  47478. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  47479. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  47480. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  47481. beginFrame = Math.max(beginFrame, this._from);
  47482. endFrame = Math.min(endFrame, this._to);
  47483. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47484. var targetedAnimation = this._targetedAnimations[index];
  47485. var keys = targetedAnimation.animation.getKeys();
  47486. var startKey = keys[0];
  47487. var endKey = keys[keys.length - 1];
  47488. if (startKey.frame > beginFrame) {
  47489. var newKey = {
  47490. frame: beginFrame,
  47491. value: startKey.value,
  47492. inTangent: startKey.inTangent,
  47493. outTangent: startKey.outTangent,
  47494. interpolation: startKey.interpolation
  47495. };
  47496. keys.splice(0, 0, newKey);
  47497. }
  47498. if (endKey.frame < endFrame) {
  47499. var newKey = {
  47500. frame: endFrame,
  47501. value: endKey.value,
  47502. inTangent: endKey.outTangent,
  47503. outTangent: endKey.outTangent,
  47504. interpolation: endKey.interpolation
  47505. };
  47506. keys.push(newKey);
  47507. }
  47508. }
  47509. return this;
  47510. };
  47511. /**
  47512. * Start all animations on given targets
  47513. * @param loop defines if animations must loop
  47514. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  47515. * @param from defines the from key (optional)
  47516. * @param to defines the to key (optional)
  47517. * @returns the current animation group
  47518. */
  47519. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  47520. var _this = this;
  47521. if (loop === void 0) { loop = false; }
  47522. if (speedRatio === void 0) { speedRatio = 1; }
  47523. if (this._isStarted || this._targetedAnimations.length === 0) {
  47524. return this;
  47525. }
  47526. var _loop_1 = function () {
  47527. var targetedAnimation = this_1._targetedAnimations[index];
  47528. if (!targetedAnimation.target.animations) {
  47529. targetedAnimation.target.animations = [];
  47530. }
  47531. if (targetedAnimation.target.animations.indexOf(targetedAnimation.animation) === -1) {
  47532. targetedAnimation.target.animations.push(targetedAnimation.animation);
  47533. }
  47534. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio, function () {
  47535. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  47536. }));
  47537. };
  47538. var this_1 = this;
  47539. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47540. _loop_1();
  47541. }
  47542. this._speedRatio = speedRatio;
  47543. this._isStarted = true;
  47544. return this;
  47545. };
  47546. /**
  47547. * Pause all animations
  47548. */
  47549. AnimationGroup.prototype.pause = function () {
  47550. if (!this._isStarted) {
  47551. return this;
  47552. }
  47553. for (var index = 0; index < this._animatables.length; index++) {
  47554. var animatable = this._animatables[index];
  47555. animatable.pause();
  47556. }
  47557. return this;
  47558. };
  47559. /**
  47560. * Play all animations to initial state
  47561. * This function will start() the animations if they were not started or will restart() them if they were paused
  47562. * @param loop defines if animations must loop
  47563. */
  47564. AnimationGroup.prototype.play = function (loop) {
  47565. if (this.isStarted) {
  47566. if (loop !== undefined) {
  47567. for (var index = 0; index < this._animatables.length; index++) {
  47568. var animatable = this._animatables[index];
  47569. animatable.loopAnimation = loop;
  47570. }
  47571. }
  47572. this.restart();
  47573. }
  47574. else {
  47575. this.start(loop, this._speedRatio);
  47576. }
  47577. return this;
  47578. };
  47579. /**
  47580. * Reset all animations to initial state
  47581. */
  47582. AnimationGroup.prototype.reset = function () {
  47583. if (!this._isStarted) {
  47584. return this;
  47585. }
  47586. for (var index = 0; index < this._animatables.length; index++) {
  47587. var animatable = this._animatables[index];
  47588. animatable.reset();
  47589. }
  47590. return this;
  47591. };
  47592. /**
  47593. * Restart animations from key 0
  47594. */
  47595. AnimationGroup.prototype.restart = function () {
  47596. if (!this._isStarted) {
  47597. return this;
  47598. }
  47599. for (var index = 0; index < this._animatables.length; index++) {
  47600. var animatable = this._animatables[index];
  47601. animatable.restart();
  47602. }
  47603. return this;
  47604. };
  47605. /**
  47606. * Stop all animations
  47607. */
  47608. AnimationGroup.prototype.stop = function () {
  47609. if (!this._isStarted) {
  47610. return this;
  47611. }
  47612. for (var index = 0; index < this._animatables.length; index++) {
  47613. var animatable = this._animatables[index];
  47614. animatable.stop();
  47615. }
  47616. this._isStarted = false;
  47617. return this;
  47618. };
  47619. /**
  47620. * Goes to a specific frame in this animation group
  47621. *
  47622. * @param frame the frame number to go to
  47623. * @return the animationGroup
  47624. */
  47625. AnimationGroup.prototype.goToFrame = function (frame) {
  47626. if (!this._isStarted) {
  47627. return this;
  47628. }
  47629. for (var index = 0; index < this._animatables.length; index++) {
  47630. var animatable = this._animatables[index];
  47631. animatable.goToFrame(frame);
  47632. }
  47633. return this;
  47634. };
  47635. /**
  47636. * Dispose all associated resources
  47637. */
  47638. AnimationGroup.prototype.dispose = function () {
  47639. this._targetedAnimations = [];
  47640. this._animatables = [];
  47641. var index = this._scene.animationGroups.indexOf(this);
  47642. if (index > -1) {
  47643. this._scene.animationGroups.splice(index, 1);
  47644. }
  47645. };
  47646. return AnimationGroup;
  47647. }());
  47648. BABYLON.AnimationGroup = AnimationGroup;
  47649. })(BABYLON || (BABYLON = {}));
  47650. //# sourceMappingURL=babylon.animationGroup.js.map
  47651. "use strict";
  47652. var BABYLON;
  47653. (function (BABYLON) {
  47654. var RuntimeAnimation = /** @class */ (function () {
  47655. /**
  47656. * Create a new RuntimeAnimation object
  47657. * @param target defines the target of the animation
  47658. * @param animation defines the source {BABYLON.Animation} object
  47659. * @param scene defines the hosting scene
  47660. * @param host defines the initiating Animatable
  47661. */
  47662. function RuntimeAnimation(target, animation, scene, host) {
  47663. this._currentFrame = 0;
  47664. this._offsetsCache = {};
  47665. this._highLimitsCache = {};
  47666. this._stopped = false;
  47667. this._blendingFactor = 0;
  47668. this._targetPath = "";
  47669. this._weight = 1.0;
  47670. this._ratioOffset = 0;
  47671. this._previousDelay = 0;
  47672. this._previousRatio = 0;
  47673. this._animation = animation;
  47674. this._target = target;
  47675. this._scene = scene;
  47676. this._host = host;
  47677. animation._runtimeAnimations.push(this);
  47678. }
  47679. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  47680. /**
  47681. * Gets the current frame
  47682. */
  47683. get: function () {
  47684. return this._currentFrame;
  47685. },
  47686. enumerable: true,
  47687. configurable: true
  47688. });
  47689. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  47690. /**
  47691. * Gets the weight of the runtime animation
  47692. */
  47693. get: function () {
  47694. return this._weight;
  47695. },
  47696. enumerable: true,
  47697. configurable: true
  47698. });
  47699. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  47700. /**
  47701. * Gets the original value of the runtime animation
  47702. */
  47703. get: function () {
  47704. return this._originalValue;
  47705. },
  47706. enumerable: true,
  47707. configurable: true
  47708. });
  47709. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  47710. /**
  47711. * Gets the current value of the runtime animation
  47712. */
  47713. get: function () {
  47714. return this._currentValue;
  47715. },
  47716. enumerable: true,
  47717. configurable: true
  47718. });
  47719. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  47720. /**
  47721. * Gets the path where to store the animated value in the target
  47722. */
  47723. get: function () {
  47724. return this._targetPath;
  47725. },
  47726. enumerable: true,
  47727. configurable: true
  47728. });
  47729. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  47730. /**
  47731. * Gets the actual target of the runtime animation
  47732. */
  47733. get: function () {
  47734. return this._activeTarget;
  47735. },
  47736. enumerable: true,
  47737. configurable: true
  47738. });
  47739. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  47740. get: function () {
  47741. return this._animation;
  47742. },
  47743. enumerable: true,
  47744. configurable: true
  47745. });
  47746. RuntimeAnimation.prototype.reset = function () {
  47747. this._offsetsCache = {};
  47748. this._highLimitsCache = {};
  47749. this._currentFrame = 0;
  47750. this._blendingFactor = 0;
  47751. this._originalValue = null;
  47752. };
  47753. RuntimeAnimation.prototype.isStopped = function () {
  47754. return this._stopped;
  47755. };
  47756. RuntimeAnimation.prototype.dispose = function () {
  47757. var index = this._animation.runtimeAnimations.indexOf(this);
  47758. if (index > -1) {
  47759. this._animation.runtimeAnimations.splice(index, 1);
  47760. }
  47761. };
  47762. RuntimeAnimation.prototype._getKeyValue = function (value) {
  47763. if (typeof value === "function") {
  47764. return value();
  47765. }
  47766. return value;
  47767. };
  47768. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  47769. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  47770. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  47771. }
  47772. this._currentFrame = currentFrame;
  47773. var keys = this._animation.getKeys();
  47774. // Try to get a hash to find the right key
  47775. 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));
  47776. if (keys[startKeyIndex].frame >= currentFrame) {
  47777. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  47778. startKeyIndex--;
  47779. }
  47780. }
  47781. for (var key = startKeyIndex; key < keys.length; key++) {
  47782. var endKey = keys[key + 1];
  47783. if (endKey.frame >= currentFrame) {
  47784. var startKey = keys[key];
  47785. var startValue = this._getKeyValue(startKey.value);
  47786. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  47787. return startValue;
  47788. }
  47789. var endValue = this._getKeyValue(endKey.value);
  47790. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47791. var frameDelta = endKey.frame - startKey.frame;
  47792. // gradient : percent of currentFrame between the frame inf and the frame sup
  47793. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47794. // check for easingFunction and correction of gradient
  47795. var easingFunction = this._animation.getEasingFunction();
  47796. if (easingFunction != null) {
  47797. gradient = easingFunction.ease(gradient);
  47798. }
  47799. switch (this._animation.dataType) {
  47800. // Float
  47801. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47802. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47803. switch (loopMode) {
  47804. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47805. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47806. return floatValue;
  47807. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47808. return offsetValue * repeatCount + floatValue;
  47809. }
  47810. break;
  47811. // Quaternion
  47812. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47813. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47814. switch (loopMode) {
  47815. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47816. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47817. return quatValue;
  47818. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47819. return quatValue.add(offsetValue.scale(repeatCount));
  47820. }
  47821. return quatValue;
  47822. // Vector3
  47823. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47824. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47825. switch (loopMode) {
  47826. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47827. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47828. return vec3Value;
  47829. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47830. return vec3Value.add(offsetValue.scale(repeatCount));
  47831. }
  47832. // Vector2
  47833. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47834. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47835. switch (loopMode) {
  47836. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47837. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47838. return vec2Value;
  47839. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47840. return vec2Value.add(offsetValue.scale(repeatCount));
  47841. }
  47842. // Size
  47843. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47844. switch (loopMode) {
  47845. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47846. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47847. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47848. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47849. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47850. }
  47851. // Color3
  47852. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47853. switch (loopMode) {
  47854. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47855. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47856. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47857. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47858. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47859. }
  47860. // Matrix
  47861. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47862. switch (loopMode) {
  47863. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47864. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47865. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47866. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47867. }
  47868. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47869. return startValue;
  47870. }
  47871. default:
  47872. break;
  47873. }
  47874. break;
  47875. }
  47876. }
  47877. return this._getKeyValue(keys[keys.length - 1].value);
  47878. };
  47879. /**
  47880. * Affect the interpolated value to the target
  47881. * @param currentValue defines the value computed by the animation
  47882. * @param weight defines the weight to apply to this value
  47883. */
  47884. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  47885. if (weight === void 0) { weight = 1.0; }
  47886. // Set value
  47887. var path;
  47888. var destination;
  47889. var targetPropertyPath = this._animation.targetPropertyPath;
  47890. if (targetPropertyPath.length > 1) {
  47891. var property = this._target[targetPropertyPath[0]];
  47892. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47893. property = property[targetPropertyPath[index]];
  47894. }
  47895. path = targetPropertyPath[targetPropertyPath.length - 1];
  47896. destination = property;
  47897. }
  47898. else {
  47899. path = targetPropertyPath[0];
  47900. destination = this._target;
  47901. }
  47902. this._targetPath = path;
  47903. this._activeTarget = destination;
  47904. this._weight = weight;
  47905. // Blending
  47906. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  47907. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  47908. if (enableBlending && this._blendingFactor <= 1.0) {
  47909. if (!this._originalBlendValue) {
  47910. var originalValue = destination[path];
  47911. if (originalValue.clone) {
  47912. this._originalBlendValue = originalValue.clone();
  47913. }
  47914. else {
  47915. this._originalBlendValue = originalValue;
  47916. }
  47917. }
  47918. }
  47919. if (weight !== -1.0) {
  47920. if (!this._originalValue) {
  47921. var originalValue = void 0;
  47922. if (destination.getRestPose) {
  47923. originalValue = destination.getRestPose();
  47924. }
  47925. else {
  47926. originalValue = destination[path];
  47927. }
  47928. if (originalValue.clone) {
  47929. this._originalValue = originalValue.clone();
  47930. }
  47931. else {
  47932. this._originalValue = originalValue;
  47933. }
  47934. }
  47935. }
  47936. if (enableBlending && this._blendingFactor <= 1.0) {
  47937. if (this._originalBlendValue.prototype) {
  47938. if (this._originalBlendValue.prototype.Lerp) {
  47939. this._currentValue = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  47940. }
  47941. else {
  47942. this._currentValue = currentValue;
  47943. }
  47944. }
  47945. else if (this._originalBlendValue.m) {
  47946. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  47947. }
  47948. else {
  47949. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  47950. }
  47951. this._blendingFactor += blendingSpeed;
  47952. }
  47953. else {
  47954. this._currentValue = currentValue;
  47955. }
  47956. if (weight !== -1.0) {
  47957. this._scene._registerTargetForLateAnimationBinding(this);
  47958. }
  47959. else {
  47960. destination[path] = this._currentValue;
  47961. }
  47962. if (this._target.markAsDirty) {
  47963. this._target.markAsDirty(this._animation.targetProperty);
  47964. }
  47965. };
  47966. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  47967. if (this._target && this._target.animationPropertiesOverride) {
  47968. return this._target.animationPropertiesOverride.loopMode;
  47969. }
  47970. return this._animation.loopMode;
  47971. };
  47972. /**
  47973. * Move the current animation to a given frame
  47974. * @param frame defines the frame to move to
  47975. */
  47976. RuntimeAnimation.prototype.goToFrame = function (frame) {
  47977. var keys = this._animation.getKeys();
  47978. if (frame < keys[0].frame) {
  47979. frame = keys[0].frame;
  47980. }
  47981. else if (frame > keys[keys.length - 1].frame) {
  47982. frame = keys[keys.length - 1].frame;
  47983. }
  47984. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  47985. this.setValue(currentValue, -1);
  47986. };
  47987. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  47988. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  47989. this._ratioOffset = this._previousRatio - newRatio;
  47990. };
  47991. /**
  47992. * Execute the current animation
  47993. * @param delay defines the delay to add to the current frame
  47994. * @param from defines the lower bound of the animation range
  47995. * @param to defines the upper bound of the animation range
  47996. * @param loop defines if the current animation must loop
  47997. * @param speedRatio defines the current speed ratio
  47998. * @param weight defines the weight of the animation (default is -1 so no weight)
  47999. * @returns a boolean indicating if the animation has ended
  48000. */
  48001. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  48002. if (weight === void 0) { weight = -1.0; }
  48003. var targetPropertyPath = this._animation.targetPropertyPath;
  48004. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  48005. this._stopped = true;
  48006. return false;
  48007. }
  48008. var returnValue = true;
  48009. var keys = this._animation.getKeys();
  48010. // Adding a start key at frame 0 if missing
  48011. if (keys[0].frame !== 0) {
  48012. var newKey = { frame: 0, value: keys[0].value };
  48013. keys.splice(0, 0, newKey);
  48014. }
  48015. // Check limits
  48016. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  48017. from = keys[0].frame;
  48018. }
  48019. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  48020. to = keys[keys.length - 1].frame;
  48021. }
  48022. //to and from cannot be the same key
  48023. if (from === to) {
  48024. if (from > keys[0].frame) {
  48025. from--;
  48026. }
  48027. else if (to < keys[keys.length - 1].frame) {
  48028. to++;
  48029. }
  48030. }
  48031. // Compute ratio
  48032. var range = to - from;
  48033. var offsetValue;
  48034. // ratio represents the frame delta between from and to
  48035. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  48036. var highLimitValue = 0;
  48037. this._previousDelay = delay;
  48038. this._previousRatio = ratio;
  48039. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  48040. returnValue = false;
  48041. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  48042. }
  48043. else {
  48044. // Get max value if required
  48045. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  48046. var keyOffset = to.toString() + from.toString();
  48047. if (!this._offsetsCache[keyOffset]) {
  48048. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  48049. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  48050. switch (this._animation.dataType) {
  48051. // Float
  48052. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48053. this._offsetsCache[keyOffset] = toValue - fromValue;
  48054. break;
  48055. // Quaternion
  48056. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48057. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48058. break;
  48059. // Vector3
  48060. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48061. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48062. // Vector2
  48063. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48064. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48065. // Size
  48066. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48067. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48068. // Color3
  48069. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48070. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48071. default:
  48072. break;
  48073. }
  48074. this._highLimitsCache[keyOffset] = toValue;
  48075. }
  48076. highLimitValue = this._highLimitsCache[keyOffset];
  48077. offsetValue = this._offsetsCache[keyOffset];
  48078. }
  48079. }
  48080. if (offsetValue === undefined) {
  48081. switch (this._animation.dataType) {
  48082. // Float
  48083. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48084. offsetValue = 0;
  48085. break;
  48086. // Quaternion
  48087. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48088. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  48089. break;
  48090. // Vector3
  48091. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48092. offsetValue = BABYLON.Vector3.Zero();
  48093. break;
  48094. // Vector2
  48095. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48096. offsetValue = BABYLON.Vector2.Zero();
  48097. break;
  48098. // Size
  48099. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48100. offsetValue = BABYLON.Size.Zero();
  48101. break;
  48102. // Color3
  48103. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48104. offsetValue = BABYLON.Color3.Black();
  48105. }
  48106. }
  48107. // Compute value
  48108. var repeatCount = (ratio / range) >> 0;
  48109. var currentFrame = returnValue ? from + ratio % range : to;
  48110. // Need to normalize?
  48111. if (this._host && this._host.syncRoot) {
  48112. var syncRoot = this._host.syncRoot;
  48113. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  48114. currentFrame = from + (to - from) * hostNormalizedFrame;
  48115. }
  48116. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  48117. // Set value
  48118. this.setValue(currentValue, weight);
  48119. // Check events
  48120. var events = this._animation.getEvents();
  48121. for (var index = 0; index < events.length; index++) {
  48122. // Make sure current frame has passed event frame and that event frame is within the current range
  48123. // Also, handle both forward and reverse animations
  48124. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  48125. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  48126. var event = events[index];
  48127. if (!event.isDone) {
  48128. // If event should be done only once, remove it.
  48129. if (event.onlyOnce) {
  48130. events.splice(index, 1);
  48131. index--;
  48132. }
  48133. event.isDone = true;
  48134. event.action();
  48135. } // Don't do anything if the event has already be done.
  48136. }
  48137. else if (events[index].isDone && !events[index].onlyOnce) {
  48138. // reset event, the animation is looping
  48139. events[index].isDone = false;
  48140. }
  48141. }
  48142. if (!returnValue) {
  48143. this._stopped = true;
  48144. }
  48145. return returnValue;
  48146. };
  48147. return RuntimeAnimation;
  48148. }());
  48149. BABYLON.RuntimeAnimation = RuntimeAnimation;
  48150. })(BABYLON || (BABYLON = {}));
  48151. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  48152. "use strict";
  48153. var BABYLON;
  48154. (function (BABYLON) {
  48155. var Animatable = /** @class */ (function () {
  48156. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  48157. if (fromFrame === void 0) { fromFrame = 0; }
  48158. if (toFrame === void 0) { toFrame = 100; }
  48159. if (loopAnimation === void 0) { loopAnimation = false; }
  48160. if (speedRatio === void 0) { speedRatio = 1.0; }
  48161. this.target = target;
  48162. this.fromFrame = fromFrame;
  48163. this.toFrame = toFrame;
  48164. this.loopAnimation = loopAnimation;
  48165. this.onAnimationEnd = onAnimationEnd;
  48166. this._localDelayOffset = null;
  48167. this._pausedDelay = null;
  48168. this._runtimeAnimations = new Array();
  48169. this._paused = false;
  48170. this._speedRatio = 1;
  48171. this._weight = -1.0;
  48172. this.animationStarted = false;
  48173. if (animations) {
  48174. this.appendAnimations(target, animations);
  48175. }
  48176. this._speedRatio = speedRatio;
  48177. this._scene = scene;
  48178. scene._activeAnimatables.push(this);
  48179. }
  48180. Object.defineProperty(Animatable.prototype, "syncRoot", {
  48181. /**
  48182. * Gets the root Animatable used to synchronize and normalize animations
  48183. */
  48184. get: function () {
  48185. return this._syncRoot;
  48186. },
  48187. enumerable: true,
  48188. configurable: true
  48189. });
  48190. Object.defineProperty(Animatable.prototype, "masterFrame", {
  48191. /**
  48192. * Gets the current frame of the first RuntimeAnimation
  48193. * Used to synchronize Animatables
  48194. */
  48195. get: function () {
  48196. if (this._runtimeAnimations.length === 0) {
  48197. return 0;
  48198. }
  48199. return this._runtimeAnimations[0].currentFrame;
  48200. },
  48201. enumerable: true,
  48202. configurable: true
  48203. });
  48204. Object.defineProperty(Animatable.prototype, "weight", {
  48205. /**
  48206. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  48207. */
  48208. get: function () {
  48209. return this._weight;
  48210. },
  48211. set: function (value) {
  48212. if (value === -1) {
  48213. this._weight = -1;
  48214. return;
  48215. }
  48216. // Else weight must be in [0, 1] range
  48217. this._weight = Math.min(Math.max(value, 0), 1.0);
  48218. },
  48219. enumerable: true,
  48220. configurable: true
  48221. });
  48222. Object.defineProperty(Animatable.prototype, "speedRatio", {
  48223. /**
  48224. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  48225. */
  48226. get: function () {
  48227. return this._speedRatio;
  48228. },
  48229. set: function (value) {
  48230. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  48231. var animation = this._runtimeAnimations[index];
  48232. animation._prepareForSpeedRatioChange(value);
  48233. }
  48234. this._speedRatio = value;
  48235. },
  48236. enumerable: true,
  48237. configurable: true
  48238. });
  48239. // Methods
  48240. /**
  48241. * Synchronize and normalize current Animatable with a source Animatable.
  48242. * This is useful when using animation weights and when animations are not of the same length
  48243. * @param root defines the root Animatable to synchronize with
  48244. * @returns the current Animatable
  48245. */
  48246. Animatable.prototype.syncWith = function (root) {
  48247. this._syncRoot = root;
  48248. if (root) {
  48249. // Make sure this animatable will animate after the root
  48250. var index = this._scene._activeAnimatables.indexOf(this);
  48251. if (index > -1) {
  48252. this._scene._activeAnimatables.splice(index, 1);
  48253. this._scene._activeAnimatables.push(this);
  48254. }
  48255. }
  48256. return this;
  48257. };
  48258. Animatable.prototype.getAnimations = function () {
  48259. return this._runtimeAnimations;
  48260. };
  48261. Animatable.prototype.appendAnimations = function (target, animations) {
  48262. for (var index = 0; index < animations.length; index++) {
  48263. var animation = animations[index];
  48264. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  48265. }
  48266. };
  48267. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  48268. var runtimeAnimations = this._runtimeAnimations;
  48269. for (var index = 0; index < runtimeAnimations.length; index++) {
  48270. if (runtimeAnimations[index].animation.targetProperty === property) {
  48271. return runtimeAnimations[index].animation;
  48272. }
  48273. }
  48274. return null;
  48275. };
  48276. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  48277. var runtimeAnimations = this._runtimeAnimations;
  48278. for (var index = 0; index < runtimeAnimations.length; index++) {
  48279. if (runtimeAnimations[index].animation.targetProperty === property) {
  48280. return runtimeAnimations[index];
  48281. }
  48282. }
  48283. return null;
  48284. };
  48285. Animatable.prototype.reset = function () {
  48286. var runtimeAnimations = this._runtimeAnimations;
  48287. for (var index = 0; index < runtimeAnimations.length; index++) {
  48288. runtimeAnimations[index].reset();
  48289. }
  48290. // Reset to original value
  48291. for (index = 0; index < runtimeAnimations.length; index++) {
  48292. var animation = runtimeAnimations[index];
  48293. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  48294. }
  48295. this._localDelayOffset = null;
  48296. this._pausedDelay = null;
  48297. };
  48298. Animatable.prototype.enableBlending = function (blendingSpeed) {
  48299. var runtimeAnimations = this._runtimeAnimations;
  48300. for (var index = 0; index < runtimeAnimations.length; index++) {
  48301. runtimeAnimations[index].animation.enableBlending = true;
  48302. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  48303. }
  48304. };
  48305. Animatable.prototype.disableBlending = function () {
  48306. var runtimeAnimations = this._runtimeAnimations;
  48307. for (var index = 0; index < runtimeAnimations.length; index++) {
  48308. runtimeAnimations[index].animation.enableBlending = false;
  48309. }
  48310. };
  48311. Animatable.prototype.goToFrame = function (frame) {
  48312. var runtimeAnimations = this._runtimeAnimations;
  48313. if (runtimeAnimations[0]) {
  48314. var fps = runtimeAnimations[0].animation.framePerSecond;
  48315. var currentFrame = runtimeAnimations[0].currentFrame;
  48316. var adjustTime = frame - currentFrame;
  48317. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  48318. if (this._localDelayOffset === null) {
  48319. this._localDelayOffset = 0;
  48320. }
  48321. this._localDelayOffset -= delay;
  48322. }
  48323. for (var index = 0; index < runtimeAnimations.length; index++) {
  48324. runtimeAnimations[index].goToFrame(frame);
  48325. }
  48326. };
  48327. Animatable.prototype.pause = function () {
  48328. if (this._paused) {
  48329. return;
  48330. }
  48331. this._paused = true;
  48332. };
  48333. Animatable.prototype.restart = function () {
  48334. this._paused = false;
  48335. };
  48336. Animatable.prototype.stop = function (animationName) {
  48337. if (animationName) {
  48338. var idx = this._scene._activeAnimatables.indexOf(this);
  48339. if (idx > -1) {
  48340. var runtimeAnimations = this._runtimeAnimations;
  48341. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  48342. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  48343. continue;
  48344. }
  48345. runtimeAnimations[index].dispose();
  48346. runtimeAnimations.splice(index, 1);
  48347. }
  48348. if (runtimeAnimations.length == 0) {
  48349. this._scene._activeAnimatables.splice(idx, 1);
  48350. if (this.onAnimationEnd) {
  48351. this.onAnimationEnd();
  48352. }
  48353. }
  48354. }
  48355. }
  48356. else {
  48357. var index = this._scene._activeAnimatables.indexOf(this);
  48358. if (index > -1) {
  48359. this._scene._activeAnimatables.splice(index, 1);
  48360. var runtimeAnimations = this._runtimeAnimations;
  48361. for (var index = 0; index < runtimeAnimations.length; index++) {
  48362. runtimeAnimations[index].dispose();
  48363. }
  48364. if (this.onAnimationEnd) {
  48365. this.onAnimationEnd();
  48366. }
  48367. }
  48368. }
  48369. };
  48370. Animatable.prototype._animate = function (delay) {
  48371. if (this._paused) {
  48372. this.animationStarted = false;
  48373. if (this._pausedDelay === null) {
  48374. this._pausedDelay = delay;
  48375. }
  48376. return true;
  48377. }
  48378. if (this._localDelayOffset === null) {
  48379. this._localDelayOffset = delay;
  48380. this._pausedDelay = null;
  48381. }
  48382. else if (this._pausedDelay !== null) {
  48383. this._localDelayOffset += delay - this._pausedDelay;
  48384. this._pausedDelay = null;
  48385. }
  48386. if (this._weight === 0) {
  48387. return true;
  48388. }
  48389. // Animating
  48390. var running = false;
  48391. var runtimeAnimations = this._runtimeAnimations;
  48392. var index;
  48393. for (index = 0; index < runtimeAnimations.length; index++) {
  48394. var animation = runtimeAnimations[index];
  48395. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  48396. running = running || isRunning;
  48397. }
  48398. this.animationStarted = running;
  48399. if (!running) {
  48400. // Remove from active animatables
  48401. index = this._scene._activeAnimatables.indexOf(this);
  48402. this._scene._activeAnimatables.splice(index, 1);
  48403. // Dispose all runtime animations
  48404. for (index = 0; index < runtimeAnimations.length; index++) {
  48405. runtimeAnimations[index].dispose();
  48406. }
  48407. }
  48408. if (!running && this.onAnimationEnd) {
  48409. this.onAnimationEnd();
  48410. this.onAnimationEnd = null;
  48411. }
  48412. return running;
  48413. };
  48414. return Animatable;
  48415. }());
  48416. BABYLON.Animatable = Animatable;
  48417. })(BABYLON || (BABYLON = {}));
  48418. //# sourceMappingURL=babylon.animatable.js.map
  48419. "use strict";
  48420. var BABYLON;
  48421. (function (BABYLON) {
  48422. var EasingFunction = /** @class */ (function () {
  48423. function EasingFunction() {
  48424. // Properties
  48425. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  48426. }
  48427. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  48428. get: function () {
  48429. return EasingFunction._EASINGMODE_EASEIN;
  48430. },
  48431. enumerable: true,
  48432. configurable: true
  48433. });
  48434. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  48435. get: function () {
  48436. return EasingFunction._EASINGMODE_EASEOUT;
  48437. },
  48438. enumerable: true,
  48439. configurable: true
  48440. });
  48441. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  48442. get: function () {
  48443. return EasingFunction._EASINGMODE_EASEINOUT;
  48444. },
  48445. enumerable: true,
  48446. configurable: true
  48447. });
  48448. EasingFunction.prototype.setEasingMode = function (easingMode) {
  48449. var n = Math.min(Math.max(easingMode, 0), 2);
  48450. this._easingMode = n;
  48451. };
  48452. EasingFunction.prototype.getEasingMode = function () {
  48453. return this._easingMode;
  48454. };
  48455. EasingFunction.prototype.easeInCore = function (gradient) {
  48456. throw new Error('You must implement this method');
  48457. };
  48458. EasingFunction.prototype.ease = function (gradient) {
  48459. switch (this._easingMode) {
  48460. case EasingFunction.EASINGMODE_EASEIN:
  48461. return this.easeInCore(gradient);
  48462. case EasingFunction.EASINGMODE_EASEOUT:
  48463. return (1 - this.easeInCore(1 - gradient));
  48464. }
  48465. if (gradient >= 0.5) {
  48466. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  48467. }
  48468. return (this.easeInCore(gradient * 2) * 0.5);
  48469. };
  48470. //Statics
  48471. EasingFunction._EASINGMODE_EASEIN = 0;
  48472. EasingFunction._EASINGMODE_EASEOUT = 1;
  48473. EasingFunction._EASINGMODE_EASEINOUT = 2;
  48474. return EasingFunction;
  48475. }());
  48476. BABYLON.EasingFunction = EasingFunction;
  48477. var CircleEase = /** @class */ (function (_super) {
  48478. __extends(CircleEase, _super);
  48479. function CircleEase() {
  48480. return _super !== null && _super.apply(this, arguments) || this;
  48481. }
  48482. CircleEase.prototype.easeInCore = function (gradient) {
  48483. gradient = Math.max(0, Math.min(1, gradient));
  48484. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  48485. };
  48486. return CircleEase;
  48487. }(EasingFunction));
  48488. BABYLON.CircleEase = CircleEase;
  48489. var BackEase = /** @class */ (function (_super) {
  48490. __extends(BackEase, _super);
  48491. function BackEase(amplitude) {
  48492. if (amplitude === void 0) { amplitude = 1; }
  48493. var _this = _super.call(this) || this;
  48494. _this.amplitude = amplitude;
  48495. return _this;
  48496. }
  48497. BackEase.prototype.easeInCore = function (gradient) {
  48498. var num = Math.max(0, this.amplitude);
  48499. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  48500. };
  48501. return BackEase;
  48502. }(EasingFunction));
  48503. BABYLON.BackEase = BackEase;
  48504. var BounceEase = /** @class */ (function (_super) {
  48505. __extends(BounceEase, _super);
  48506. function BounceEase(bounces, bounciness) {
  48507. if (bounces === void 0) { bounces = 3; }
  48508. if (bounciness === void 0) { bounciness = 2; }
  48509. var _this = _super.call(this) || this;
  48510. _this.bounces = bounces;
  48511. _this.bounciness = bounciness;
  48512. return _this;
  48513. }
  48514. BounceEase.prototype.easeInCore = function (gradient) {
  48515. var y = Math.max(0.0, this.bounces);
  48516. var bounciness = this.bounciness;
  48517. if (bounciness <= 1.0) {
  48518. bounciness = 1.001;
  48519. }
  48520. var num9 = Math.pow(bounciness, y);
  48521. var num5 = 1.0 - bounciness;
  48522. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  48523. var num15 = gradient * num4;
  48524. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  48525. var num3 = Math.floor(num65);
  48526. var num13 = num3 + 1.0;
  48527. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  48528. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  48529. var num7 = (num8 + num12) * 0.5;
  48530. var num6 = gradient - num7;
  48531. var num2 = num7 - num8;
  48532. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  48533. };
  48534. return BounceEase;
  48535. }(EasingFunction));
  48536. BABYLON.BounceEase = BounceEase;
  48537. var CubicEase = /** @class */ (function (_super) {
  48538. __extends(CubicEase, _super);
  48539. function CubicEase() {
  48540. return _super !== null && _super.apply(this, arguments) || this;
  48541. }
  48542. CubicEase.prototype.easeInCore = function (gradient) {
  48543. return (gradient * gradient * gradient);
  48544. };
  48545. return CubicEase;
  48546. }(EasingFunction));
  48547. BABYLON.CubicEase = CubicEase;
  48548. var ElasticEase = /** @class */ (function (_super) {
  48549. __extends(ElasticEase, _super);
  48550. function ElasticEase(oscillations, springiness) {
  48551. if (oscillations === void 0) { oscillations = 3; }
  48552. if (springiness === void 0) { springiness = 3; }
  48553. var _this = _super.call(this) || this;
  48554. _this.oscillations = oscillations;
  48555. _this.springiness = springiness;
  48556. return _this;
  48557. }
  48558. ElasticEase.prototype.easeInCore = function (gradient) {
  48559. var num2;
  48560. var num3 = Math.max(0.0, this.oscillations);
  48561. var num = Math.max(0.0, this.springiness);
  48562. if (num == 0) {
  48563. num2 = gradient;
  48564. }
  48565. else {
  48566. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  48567. }
  48568. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  48569. };
  48570. return ElasticEase;
  48571. }(EasingFunction));
  48572. BABYLON.ElasticEase = ElasticEase;
  48573. var ExponentialEase = /** @class */ (function (_super) {
  48574. __extends(ExponentialEase, _super);
  48575. function ExponentialEase(exponent) {
  48576. if (exponent === void 0) { exponent = 2; }
  48577. var _this = _super.call(this) || this;
  48578. _this.exponent = exponent;
  48579. return _this;
  48580. }
  48581. ExponentialEase.prototype.easeInCore = function (gradient) {
  48582. if (this.exponent <= 0) {
  48583. return gradient;
  48584. }
  48585. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  48586. };
  48587. return ExponentialEase;
  48588. }(EasingFunction));
  48589. BABYLON.ExponentialEase = ExponentialEase;
  48590. var PowerEase = /** @class */ (function (_super) {
  48591. __extends(PowerEase, _super);
  48592. function PowerEase(power) {
  48593. if (power === void 0) { power = 2; }
  48594. var _this = _super.call(this) || this;
  48595. _this.power = power;
  48596. return _this;
  48597. }
  48598. PowerEase.prototype.easeInCore = function (gradient) {
  48599. var y = Math.max(0.0, this.power);
  48600. return Math.pow(gradient, y);
  48601. };
  48602. return PowerEase;
  48603. }(EasingFunction));
  48604. BABYLON.PowerEase = PowerEase;
  48605. var QuadraticEase = /** @class */ (function (_super) {
  48606. __extends(QuadraticEase, _super);
  48607. function QuadraticEase() {
  48608. return _super !== null && _super.apply(this, arguments) || this;
  48609. }
  48610. QuadraticEase.prototype.easeInCore = function (gradient) {
  48611. return (gradient * gradient);
  48612. };
  48613. return QuadraticEase;
  48614. }(EasingFunction));
  48615. BABYLON.QuadraticEase = QuadraticEase;
  48616. var QuarticEase = /** @class */ (function (_super) {
  48617. __extends(QuarticEase, _super);
  48618. function QuarticEase() {
  48619. return _super !== null && _super.apply(this, arguments) || this;
  48620. }
  48621. QuarticEase.prototype.easeInCore = function (gradient) {
  48622. return (gradient * gradient * gradient * gradient);
  48623. };
  48624. return QuarticEase;
  48625. }(EasingFunction));
  48626. BABYLON.QuarticEase = QuarticEase;
  48627. var QuinticEase = /** @class */ (function (_super) {
  48628. __extends(QuinticEase, _super);
  48629. function QuinticEase() {
  48630. return _super !== null && _super.apply(this, arguments) || this;
  48631. }
  48632. QuinticEase.prototype.easeInCore = function (gradient) {
  48633. return (gradient * gradient * gradient * gradient * gradient);
  48634. };
  48635. return QuinticEase;
  48636. }(EasingFunction));
  48637. BABYLON.QuinticEase = QuinticEase;
  48638. var SineEase = /** @class */ (function (_super) {
  48639. __extends(SineEase, _super);
  48640. function SineEase() {
  48641. return _super !== null && _super.apply(this, arguments) || this;
  48642. }
  48643. SineEase.prototype.easeInCore = function (gradient) {
  48644. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  48645. };
  48646. return SineEase;
  48647. }(EasingFunction));
  48648. BABYLON.SineEase = SineEase;
  48649. var BezierCurveEase = /** @class */ (function (_super) {
  48650. __extends(BezierCurveEase, _super);
  48651. function BezierCurveEase(x1, y1, x2, y2) {
  48652. if (x1 === void 0) { x1 = 0; }
  48653. if (y1 === void 0) { y1 = 0; }
  48654. if (x2 === void 0) { x2 = 1; }
  48655. if (y2 === void 0) { y2 = 1; }
  48656. var _this = _super.call(this) || this;
  48657. _this.x1 = x1;
  48658. _this.y1 = y1;
  48659. _this.x2 = x2;
  48660. _this.y2 = y2;
  48661. return _this;
  48662. }
  48663. BezierCurveEase.prototype.easeInCore = function (gradient) {
  48664. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  48665. };
  48666. return BezierCurveEase;
  48667. }(EasingFunction));
  48668. BABYLON.BezierCurveEase = BezierCurveEase;
  48669. })(BABYLON || (BABYLON = {}));
  48670. //# sourceMappingURL=babylon.easing.js.map
  48671. "use strict";
  48672. var BABYLON;
  48673. (function (BABYLON) {
  48674. var Condition = /** @class */ (function () {
  48675. function Condition(actionManager) {
  48676. this._actionManager = actionManager;
  48677. }
  48678. Condition.prototype.isValid = function () {
  48679. return true;
  48680. };
  48681. Condition.prototype._getProperty = function (propertyPath) {
  48682. return this._actionManager._getProperty(propertyPath);
  48683. };
  48684. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  48685. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48686. };
  48687. Condition.prototype.serialize = function () {
  48688. };
  48689. Condition.prototype._serialize = function (serializedCondition) {
  48690. return {
  48691. type: 2,
  48692. children: [],
  48693. name: serializedCondition.name,
  48694. properties: serializedCondition.properties
  48695. };
  48696. };
  48697. return Condition;
  48698. }());
  48699. BABYLON.Condition = Condition;
  48700. var ValueCondition = /** @class */ (function (_super) {
  48701. __extends(ValueCondition, _super);
  48702. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  48703. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  48704. var _this = _super.call(this, actionManager) || this;
  48705. _this.propertyPath = propertyPath;
  48706. _this.value = value;
  48707. _this.operator = operator;
  48708. _this._target = target;
  48709. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  48710. _this._property = _this._getProperty(_this.propertyPath);
  48711. return _this;
  48712. }
  48713. Object.defineProperty(ValueCondition, "IsEqual", {
  48714. get: function () {
  48715. return ValueCondition._IsEqual;
  48716. },
  48717. enumerable: true,
  48718. configurable: true
  48719. });
  48720. Object.defineProperty(ValueCondition, "IsDifferent", {
  48721. get: function () {
  48722. return ValueCondition._IsDifferent;
  48723. },
  48724. enumerable: true,
  48725. configurable: true
  48726. });
  48727. Object.defineProperty(ValueCondition, "IsGreater", {
  48728. get: function () {
  48729. return ValueCondition._IsGreater;
  48730. },
  48731. enumerable: true,
  48732. configurable: true
  48733. });
  48734. Object.defineProperty(ValueCondition, "IsLesser", {
  48735. get: function () {
  48736. return ValueCondition._IsLesser;
  48737. },
  48738. enumerable: true,
  48739. configurable: true
  48740. });
  48741. // Methods
  48742. ValueCondition.prototype.isValid = function () {
  48743. switch (this.operator) {
  48744. case ValueCondition.IsGreater:
  48745. return this._effectiveTarget[this._property] > this.value;
  48746. case ValueCondition.IsLesser:
  48747. return this._effectiveTarget[this._property] < this.value;
  48748. case ValueCondition.IsEqual:
  48749. case ValueCondition.IsDifferent:
  48750. var check;
  48751. if (this.value.equals) {
  48752. check = this.value.equals(this._effectiveTarget[this._property]);
  48753. }
  48754. else {
  48755. check = this.value === this._effectiveTarget[this._property];
  48756. }
  48757. return this.operator === ValueCondition.IsEqual ? check : !check;
  48758. }
  48759. return false;
  48760. };
  48761. ValueCondition.prototype.serialize = function () {
  48762. return this._serialize({
  48763. name: "ValueCondition",
  48764. properties: [
  48765. BABYLON.Action._GetTargetProperty(this._target),
  48766. { name: "propertyPath", value: this.propertyPath },
  48767. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48768. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  48769. ]
  48770. });
  48771. };
  48772. ValueCondition.GetOperatorName = function (operator) {
  48773. switch (operator) {
  48774. case ValueCondition._IsEqual: return "IsEqual";
  48775. case ValueCondition._IsDifferent: return "IsDifferent";
  48776. case ValueCondition._IsGreater: return "IsGreater";
  48777. case ValueCondition._IsLesser: return "IsLesser";
  48778. default: return "";
  48779. }
  48780. };
  48781. // Statics
  48782. ValueCondition._IsEqual = 0;
  48783. ValueCondition._IsDifferent = 1;
  48784. ValueCondition._IsGreater = 2;
  48785. ValueCondition._IsLesser = 3;
  48786. return ValueCondition;
  48787. }(Condition));
  48788. BABYLON.ValueCondition = ValueCondition;
  48789. var PredicateCondition = /** @class */ (function (_super) {
  48790. __extends(PredicateCondition, _super);
  48791. function PredicateCondition(actionManager, predicate) {
  48792. var _this = _super.call(this, actionManager) || this;
  48793. _this.predicate = predicate;
  48794. return _this;
  48795. }
  48796. PredicateCondition.prototype.isValid = function () {
  48797. return this.predicate();
  48798. };
  48799. return PredicateCondition;
  48800. }(Condition));
  48801. BABYLON.PredicateCondition = PredicateCondition;
  48802. var StateCondition = /** @class */ (function (_super) {
  48803. __extends(StateCondition, _super);
  48804. function StateCondition(actionManager, target, value) {
  48805. var _this = _super.call(this, actionManager) || this;
  48806. _this.value = value;
  48807. _this._target = target;
  48808. return _this;
  48809. }
  48810. // Methods
  48811. StateCondition.prototype.isValid = function () {
  48812. return this._target.state === this.value;
  48813. };
  48814. StateCondition.prototype.serialize = function () {
  48815. return this._serialize({
  48816. name: "StateCondition",
  48817. properties: [
  48818. BABYLON.Action._GetTargetProperty(this._target),
  48819. { name: "value", value: this.value }
  48820. ]
  48821. });
  48822. };
  48823. return StateCondition;
  48824. }(Condition));
  48825. BABYLON.StateCondition = StateCondition;
  48826. })(BABYLON || (BABYLON = {}));
  48827. //# sourceMappingURL=babylon.condition.js.map
  48828. "use strict";
  48829. var BABYLON;
  48830. (function (BABYLON) {
  48831. var Action = /** @class */ (function () {
  48832. function Action(triggerOptions, condition) {
  48833. this.triggerOptions = triggerOptions;
  48834. this.onBeforeExecuteObservable = new BABYLON.Observable();
  48835. if (triggerOptions.parameter) {
  48836. this.trigger = triggerOptions.trigger;
  48837. this._triggerParameter = triggerOptions.parameter;
  48838. }
  48839. else {
  48840. this.trigger = triggerOptions;
  48841. }
  48842. this._nextActiveAction = this;
  48843. this._condition = condition;
  48844. }
  48845. // Methods
  48846. Action.prototype._prepare = function () {
  48847. };
  48848. Action.prototype.getTriggerParameter = function () {
  48849. return this._triggerParameter;
  48850. };
  48851. Action.prototype._executeCurrent = function (evt) {
  48852. if (this._nextActiveAction._condition) {
  48853. var condition = this._nextActiveAction._condition;
  48854. var currentRenderId = this._actionManager.getScene().getRenderId();
  48855. // We cache the current evaluation for the current frame
  48856. if (condition._evaluationId === currentRenderId) {
  48857. if (!condition._currentResult) {
  48858. return;
  48859. }
  48860. }
  48861. else {
  48862. condition._evaluationId = currentRenderId;
  48863. if (!condition.isValid()) {
  48864. condition._currentResult = false;
  48865. return;
  48866. }
  48867. condition._currentResult = true;
  48868. }
  48869. }
  48870. this.onBeforeExecuteObservable.notifyObservers(this);
  48871. this._nextActiveAction.execute(evt);
  48872. this.skipToNextActiveAction();
  48873. };
  48874. Action.prototype.execute = function (evt) {
  48875. };
  48876. Action.prototype.skipToNextActiveAction = function () {
  48877. if (this._nextActiveAction._child) {
  48878. if (!this._nextActiveAction._child._actionManager) {
  48879. this._nextActiveAction._child._actionManager = this._actionManager;
  48880. }
  48881. this._nextActiveAction = this._nextActiveAction._child;
  48882. }
  48883. else {
  48884. this._nextActiveAction = this;
  48885. }
  48886. };
  48887. Action.prototype.then = function (action) {
  48888. this._child = action;
  48889. action._actionManager = this._actionManager;
  48890. action._prepare();
  48891. return action;
  48892. };
  48893. Action.prototype._getProperty = function (propertyPath) {
  48894. return this._actionManager._getProperty(propertyPath);
  48895. };
  48896. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  48897. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48898. };
  48899. Action.prototype.serialize = function (parent) {
  48900. };
  48901. // Called by BABYLON.Action objects in serialize(...). Internal use
  48902. Action.prototype._serialize = function (serializedAction, parent) {
  48903. var serializationObject = {
  48904. type: 1,
  48905. children: [],
  48906. name: serializedAction.name,
  48907. properties: serializedAction.properties || []
  48908. };
  48909. // Serialize child
  48910. if (this._child) {
  48911. this._child.serialize(serializationObject);
  48912. }
  48913. // Check if "this" has a condition
  48914. if (this._condition) {
  48915. var serializedCondition = this._condition.serialize();
  48916. serializedCondition.children.push(serializationObject);
  48917. if (parent) {
  48918. parent.children.push(serializedCondition);
  48919. }
  48920. return serializedCondition;
  48921. }
  48922. if (parent) {
  48923. parent.children.push(serializationObject);
  48924. }
  48925. return serializationObject;
  48926. };
  48927. Action._SerializeValueAsString = function (value) {
  48928. if (typeof value === "number") {
  48929. return value.toString();
  48930. }
  48931. if (typeof value === "boolean") {
  48932. return value ? "true" : "false";
  48933. }
  48934. if (value instanceof BABYLON.Vector2) {
  48935. return value.x + ", " + value.y;
  48936. }
  48937. if (value instanceof BABYLON.Vector3) {
  48938. return value.x + ", " + value.y + ", " + value.z;
  48939. }
  48940. if (value instanceof BABYLON.Color3) {
  48941. return value.r + ", " + value.g + ", " + value.b;
  48942. }
  48943. if (value instanceof BABYLON.Color4) {
  48944. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  48945. }
  48946. return value; // string
  48947. };
  48948. Action._GetTargetProperty = function (target) {
  48949. return {
  48950. name: "target",
  48951. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  48952. : target instanceof BABYLON.Light ? "LightProperties"
  48953. : target instanceof BABYLON.Camera ? "CameraProperties"
  48954. : "SceneProperties",
  48955. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  48956. };
  48957. };
  48958. return Action;
  48959. }());
  48960. BABYLON.Action = Action;
  48961. })(BABYLON || (BABYLON = {}));
  48962. //# sourceMappingURL=babylon.action.js.map
  48963. "use strict";
  48964. var BABYLON;
  48965. (function (BABYLON) {
  48966. /**
  48967. * ActionEvent is the event beint sent when an action is triggered.
  48968. */
  48969. var ActionEvent = /** @class */ (function () {
  48970. /**
  48971. * @param source The mesh or sprite that triggered the action.
  48972. * @param pointerX The X mouse cursor position at the time of the event
  48973. * @param pointerY The Y mouse cursor position at the time of the event
  48974. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  48975. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  48976. */
  48977. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  48978. this.source = source;
  48979. this.pointerX = pointerX;
  48980. this.pointerY = pointerY;
  48981. this.meshUnderPointer = meshUnderPointer;
  48982. this.sourceEvent = sourceEvent;
  48983. this.additionalData = additionalData;
  48984. }
  48985. /**
  48986. * Helper function to auto-create an ActionEvent from a source mesh.
  48987. * @param source The source mesh that triggered the event
  48988. * @param evt {Event} The original (browser) event
  48989. */
  48990. ActionEvent.CreateNew = function (source, evt, additionalData) {
  48991. var scene = source.getScene();
  48992. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48993. };
  48994. /**
  48995. * Helper function to auto-create an ActionEvent from a source mesh.
  48996. * @param source The source sprite that triggered the event
  48997. * @param scene Scene associated with the sprite
  48998. * @param evt {Event} The original (browser) event
  48999. */
  49000. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  49001. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  49002. };
  49003. /**
  49004. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  49005. * @param scene the scene where the event occurred
  49006. * @param evt {Event} The original (browser) event
  49007. */
  49008. ActionEvent.CreateNewFromScene = function (scene, evt) {
  49009. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  49010. };
  49011. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  49012. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  49013. };
  49014. return ActionEvent;
  49015. }());
  49016. BABYLON.ActionEvent = ActionEvent;
  49017. /**
  49018. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  49019. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  49020. */
  49021. var ActionManager = /** @class */ (function () {
  49022. function ActionManager(scene) {
  49023. // Members
  49024. this.actions = new Array();
  49025. this.hoverCursor = '';
  49026. this._scene = scene;
  49027. scene._actionManagers.push(this);
  49028. }
  49029. Object.defineProperty(ActionManager, "NothingTrigger", {
  49030. get: function () {
  49031. return ActionManager._NothingTrigger;
  49032. },
  49033. enumerable: true,
  49034. configurable: true
  49035. });
  49036. Object.defineProperty(ActionManager, "OnPickTrigger", {
  49037. get: function () {
  49038. return ActionManager._OnPickTrigger;
  49039. },
  49040. enumerable: true,
  49041. configurable: true
  49042. });
  49043. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  49044. get: function () {
  49045. return ActionManager._OnLeftPickTrigger;
  49046. },
  49047. enumerable: true,
  49048. configurable: true
  49049. });
  49050. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  49051. get: function () {
  49052. return ActionManager._OnRightPickTrigger;
  49053. },
  49054. enumerable: true,
  49055. configurable: true
  49056. });
  49057. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  49058. get: function () {
  49059. return ActionManager._OnCenterPickTrigger;
  49060. },
  49061. enumerable: true,
  49062. configurable: true
  49063. });
  49064. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  49065. get: function () {
  49066. return ActionManager._OnPickDownTrigger;
  49067. },
  49068. enumerable: true,
  49069. configurable: true
  49070. });
  49071. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  49072. get: function () {
  49073. return ActionManager._OnDoublePickTrigger;
  49074. },
  49075. enumerable: true,
  49076. configurable: true
  49077. });
  49078. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  49079. get: function () {
  49080. return ActionManager._OnPickUpTrigger;
  49081. },
  49082. enumerable: true,
  49083. configurable: true
  49084. });
  49085. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  49086. /// This trigger will only be raised if you also declared a OnPickDown
  49087. get: function () {
  49088. return ActionManager._OnPickOutTrigger;
  49089. },
  49090. enumerable: true,
  49091. configurable: true
  49092. });
  49093. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  49094. get: function () {
  49095. return ActionManager._OnLongPressTrigger;
  49096. },
  49097. enumerable: true,
  49098. configurable: true
  49099. });
  49100. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  49101. get: function () {
  49102. return ActionManager._OnPointerOverTrigger;
  49103. },
  49104. enumerable: true,
  49105. configurable: true
  49106. });
  49107. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  49108. get: function () {
  49109. return ActionManager._OnPointerOutTrigger;
  49110. },
  49111. enumerable: true,
  49112. configurable: true
  49113. });
  49114. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  49115. get: function () {
  49116. return ActionManager._OnEveryFrameTrigger;
  49117. },
  49118. enumerable: true,
  49119. configurable: true
  49120. });
  49121. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  49122. get: function () {
  49123. return ActionManager._OnIntersectionEnterTrigger;
  49124. },
  49125. enumerable: true,
  49126. configurable: true
  49127. });
  49128. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  49129. get: function () {
  49130. return ActionManager._OnIntersectionExitTrigger;
  49131. },
  49132. enumerable: true,
  49133. configurable: true
  49134. });
  49135. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  49136. get: function () {
  49137. return ActionManager._OnKeyDownTrigger;
  49138. },
  49139. enumerable: true,
  49140. configurable: true
  49141. });
  49142. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  49143. get: function () {
  49144. return ActionManager._OnKeyUpTrigger;
  49145. },
  49146. enumerable: true,
  49147. configurable: true
  49148. });
  49149. // Methods
  49150. ActionManager.prototype.dispose = function () {
  49151. var index = this._scene._actionManagers.indexOf(this);
  49152. for (var i = 0; i < this.actions.length; i++) {
  49153. var action = this.actions[i];
  49154. ActionManager.Triggers[action.trigger]--;
  49155. if (ActionManager.Triggers[action.trigger] === 0) {
  49156. delete ActionManager.Triggers[action.trigger];
  49157. }
  49158. }
  49159. if (index > -1) {
  49160. this._scene._actionManagers.splice(index, 1);
  49161. }
  49162. };
  49163. ActionManager.prototype.getScene = function () {
  49164. return this._scene;
  49165. };
  49166. /**
  49167. * Does this action manager handles actions of any of the given triggers
  49168. * @param {number[]} triggers - the triggers to be tested
  49169. * @return {boolean} whether one (or more) of the triggers is handeled
  49170. */
  49171. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  49172. for (var index = 0; index < this.actions.length; index++) {
  49173. var action = this.actions[index];
  49174. if (triggers.indexOf(action.trigger) > -1) {
  49175. return true;
  49176. }
  49177. }
  49178. return false;
  49179. };
  49180. /**
  49181. * Does this action manager handles actions of a given trigger
  49182. * @param {number} trigger - the trigger to be tested
  49183. * @return {boolean} whether the trigger is handeled
  49184. */
  49185. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  49186. for (var index = 0; index < this.actions.length; index++) {
  49187. var action = this.actions[index];
  49188. if (action.trigger === trigger) {
  49189. return true;
  49190. }
  49191. }
  49192. return false;
  49193. };
  49194. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  49195. /**
  49196. * Does this action manager has pointer triggers
  49197. * @return {boolean} whether or not it has pointer triggers
  49198. */
  49199. get: function () {
  49200. for (var index = 0; index < this.actions.length; index++) {
  49201. var action = this.actions[index];
  49202. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  49203. return true;
  49204. }
  49205. }
  49206. return false;
  49207. },
  49208. enumerable: true,
  49209. configurable: true
  49210. });
  49211. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  49212. /**
  49213. * Does this action manager has pick triggers
  49214. * @return {boolean} whether or not it has pick triggers
  49215. */
  49216. get: function () {
  49217. for (var index = 0; index < this.actions.length; index++) {
  49218. var action = this.actions[index];
  49219. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  49220. return true;
  49221. }
  49222. }
  49223. return false;
  49224. },
  49225. enumerable: true,
  49226. configurable: true
  49227. });
  49228. Object.defineProperty(ActionManager, "HasTriggers", {
  49229. /**
  49230. * Does exist one action manager with at least one trigger
  49231. * @return {boolean} whether or not it exists one action manager with one trigger
  49232. **/
  49233. get: function () {
  49234. for (var t in ActionManager.Triggers) {
  49235. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49236. return true;
  49237. }
  49238. }
  49239. return false;
  49240. },
  49241. enumerable: true,
  49242. configurable: true
  49243. });
  49244. Object.defineProperty(ActionManager, "HasPickTriggers", {
  49245. /**
  49246. * Does exist one action manager with at least one pick trigger
  49247. * @return {boolean} whether or not it exists one action manager with one pick trigger
  49248. **/
  49249. get: function () {
  49250. for (var t in ActionManager.Triggers) {
  49251. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49252. var t_int = parseInt(t);
  49253. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  49254. return true;
  49255. }
  49256. }
  49257. }
  49258. return false;
  49259. },
  49260. enumerable: true,
  49261. configurable: true
  49262. });
  49263. /**
  49264. * Does exist one action manager that handles actions of a given trigger
  49265. * @param {number} trigger - the trigger to be tested
  49266. * @return {boolean} whether the trigger is handeled by at least one action manager
  49267. **/
  49268. ActionManager.HasSpecificTrigger = function (trigger) {
  49269. for (var t in ActionManager.Triggers) {
  49270. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49271. var t_int = parseInt(t);
  49272. if (t_int === trigger) {
  49273. return true;
  49274. }
  49275. }
  49276. }
  49277. return false;
  49278. };
  49279. /**
  49280. * Registers an action to this action manager
  49281. * @param {BABYLON.Action} action - the action to be registered
  49282. * @return {BABYLON.Action} the action amended (prepared) after registration
  49283. */
  49284. ActionManager.prototype.registerAction = function (action) {
  49285. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  49286. if (this.getScene().actionManager !== this) {
  49287. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  49288. return null;
  49289. }
  49290. }
  49291. this.actions.push(action);
  49292. if (ActionManager.Triggers[action.trigger]) {
  49293. ActionManager.Triggers[action.trigger]++;
  49294. }
  49295. else {
  49296. ActionManager.Triggers[action.trigger] = 1;
  49297. }
  49298. action._actionManager = this;
  49299. action._prepare();
  49300. return action;
  49301. };
  49302. /**
  49303. * Unregisters an action to this action manager
  49304. * @param action The action to be unregistered
  49305. * @return whether the action has been unregistered
  49306. */
  49307. ActionManager.prototype.unregisterAction = function (action) {
  49308. var index = this.actions.indexOf(action);
  49309. if (index !== -1) {
  49310. this.actions.splice(index, 1);
  49311. ActionManager.Triggers[action.trigger] -= 1;
  49312. if (ActionManager.Triggers[action.trigger] === 0) {
  49313. delete ActionManager.Triggers[action.trigger];
  49314. }
  49315. delete action._actionManager;
  49316. return true;
  49317. }
  49318. return false;
  49319. };
  49320. /**
  49321. * Process a specific trigger
  49322. * @param {number} trigger - the trigger to process
  49323. * @param evt {BABYLON.ActionEvent} the event details to be processed
  49324. */
  49325. ActionManager.prototype.processTrigger = function (trigger, evt) {
  49326. for (var index = 0; index < this.actions.length; index++) {
  49327. var action = this.actions[index];
  49328. if (action.trigger === trigger) {
  49329. if (evt) {
  49330. if (trigger === ActionManager.OnKeyUpTrigger
  49331. || trigger === ActionManager.OnKeyDownTrigger) {
  49332. var parameter = action.getTriggerParameter();
  49333. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  49334. if (!parameter.toLowerCase) {
  49335. continue;
  49336. }
  49337. var lowerCase = parameter.toLowerCase();
  49338. if (lowerCase !== evt.sourceEvent.key) {
  49339. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  49340. var actualkey = String.fromCharCode(unicode).toLowerCase();
  49341. if (actualkey !== lowerCase) {
  49342. continue;
  49343. }
  49344. }
  49345. }
  49346. }
  49347. }
  49348. action._executeCurrent(evt);
  49349. }
  49350. }
  49351. };
  49352. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  49353. var properties = propertyPath.split(".");
  49354. for (var index = 0; index < properties.length - 1; index++) {
  49355. target = target[properties[index]];
  49356. }
  49357. return target;
  49358. };
  49359. ActionManager.prototype._getProperty = function (propertyPath) {
  49360. var properties = propertyPath.split(".");
  49361. return properties[properties.length - 1];
  49362. };
  49363. ActionManager.prototype.serialize = function (name) {
  49364. var root = {
  49365. children: new Array(),
  49366. name: name,
  49367. type: 3,
  49368. properties: new Array() // Empty for root but required
  49369. };
  49370. for (var i = 0; i < this.actions.length; i++) {
  49371. var triggerObject = {
  49372. type: 0,
  49373. children: new Array(),
  49374. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  49375. properties: new Array()
  49376. };
  49377. var triggerOptions = this.actions[i].triggerOptions;
  49378. if (triggerOptions && typeof triggerOptions !== "number") {
  49379. if (triggerOptions.parameter instanceof BABYLON.Node) {
  49380. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  49381. }
  49382. else {
  49383. var parameter = {};
  49384. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  49385. if (triggerOptions.parameter.mesh) {
  49386. parameter._meshId = triggerOptions.parameter.mesh.id;
  49387. }
  49388. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  49389. }
  49390. }
  49391. // Serialize child action, recursively
  49392. this.actions[i].serialize(triggerObject);
  49393. // Add serialized trigger
  49394. root.children.push(triggerObject);
  49395. }
  49396. return root;
  49397. };
  49398. ActionManager.Parse = function (parsedActions, object, scene) {
  49399. var actionManager = new ActionManager(scene);
  49400. if (object === null)
  49401. scene.actionManager = actionManager;
  49402. else
  49403. object.actionManager = actionManager;
  49404. // instanciate a new object
  49405. var instanciate = function (name, params) {
  49406. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  49407. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  49408. newInstance.constructor.apply(newInstance, params);
  49409. return newInstance;
  49410. };
  49411. var parseParameter = function (name, value, target, propertyPath) {
  49412. if (propertyPath === null) {
  49413. // String, boolean or float
  49414. var floatValue = parseFloat(value);
  49415. if (value === "true" || value === "false")
  49416. return value === "true";
  49417. else
  49418. return isNaN(floatValue) ? value : floatValue;
  49419. }
  49420. var effectiveTarget = propertyPath.split(".");
  49421. var values = value.split(",");
  49422. // Get effective Target
  49423. for (var i = 0; i < effectiveTarget.length; i++) {
  49424. target = target[effectiveTarget[i]];
  49425. }
  49426. // Return appropriate value with its type
  49427. if (typeof (target) === "boolean")
  49428. return values[0] === "true";
  49429. if (typeof (target) === "string")
  49430. return values[0];
  49431. // Parameters with multiple values such as Vector3 etc.
  49432. var split = new Array();
  49433. for (var i = 0; i < values.length; i++)
  49434. split.push(parseFloat(values[i]));
  49435. if (target instanceof BABYLON.Vector3)
  49436. return BABYLON.Vector3.FromArray(split);
  49437. if (target instanceof BABYLON.Vector4)
  49438. return BABYLON.Vector4.FromArray(split);
  49439. if (target instanceof BABYLON.Color3)
  49440. return BABYLON.Color3.FromArray(split);
  49441. if (target instanceof BABYLON.Color4)
  49442. return BABYLON.Color4.FromArray(split);
  49443. return parseFloat(values[0]);
  49444. };
  49445. // traverse graph per trigger
  49446. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  49447. if (combineArray === void 0) { combineArray = null; }
  49448. if (parsedAction.detached)
  49449. return;
  49450. var parameters = new Array();
  49451. var target = null;
  49452. var propertyPath = null;
  49453. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  49454. // Parameters
  49455. if (parsedAction.type === 2)
  49456. parameters.push(actionManager);
  49457. else
  49458. parameters.push(trigger);
  49459. if (combine) {
  49460. var actions = new Array();
  49461. for (var j = 0; j < parsedAction.combine.length; j++) {
  49462. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  49463. }
  49464. parameters.push(actions);
  49465. }
  49466. else {
  49467. for (var i = 0; i < parsedAction.properties.length; i++) {
  49468. var value = parsedAction.properties[i].value;
  49469. var name = parsedAction.properties[i].name;
  49470. var targetType = parsedAction.properties[i].targetType;
  49471. if (name === "target")
  49472. if (targetType !== null && targetType === "SceneProperties")
  49473. value = target = scene;
  49474. else
  49475. value = target = scene.getNodeByName(value);
  49476. else if (name === "parent")
  49477. value = scene.getNodeByName(value);
  49478. else if (name === "sound")
  49479. value = scene.getSoundByName(value);
  49480. else if (name !== "propertyPath") {
  49481. if (parsedAction.type === 2 && name === "operator")
  49482. value = BABYLON.ValueCondition[value];
  49483. else
  49484. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  49485. }
  49486. else {
  49487. propertyPath = value;
  49488. }
  49489. parameters.push(value);
  49490. }
  49491. }
  49492. if (combineArray === null) {
  49493. parameters.push(condition);
  49494. }
  49495. else {
  49496. parameters.push(null);
  49497. }
  49498. // If interpolate value action
  49499. if (parsedAction.name === "InterpolateValueAction") {
  49500. var param = parameters[parameters.length - 2];
  49501. parameters[parameters.length - 1] = param;
  49502. parameters[parameters.length - 2] = condition;
  49503. }
  49504. // Action or condition(s) and not CombineAction
  49505. var newAction = instanciate(parsedAction.name, parameters);
  49506. if (newAction instanceof BABYLON.Condition && condition !== null) {
  49507. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  49508. if (action)
  49509. action.then(nothing);
  49510. else
  49511. actionManager.registerAction(nothing);
  49512. action = nothing;
  49513. }
  49514. if (combineArray === null) {
  49515. if (newAction instanceof BABYLON.Condition) {
  49516. condition = newAction;
  49517. newAction = action;
  49518. }
  49519. else {
  49520. condition = null;
  49521. if (action)
  49522. action.then(newAction);
  49523. else
  49524. actionManager.registerAction(newAction);
  49525. }
  49526. }
  49527. else {
  49528. combineArray.push(newAction);
  49529. }
  49530. for (var i = 0; i < parsedAction.children.length; i++)
  49531. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  49532. };
  49533. // triggers
  49534. for (var i = 0; i < parsedActions.children.length; i++) {
  49535. var triggerParams;
  49536. var trigger = parsedActions.children[i];
  49537. if (trigger.properties.length > 0) {
  49538. var param = trigger.properties[0].value;
  49539. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  49540. if (value._meshId) {
  49541. value.mesh = scene.getMeshByID(value._meshId);
  49542. }
  49543. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  49544. }
  49545. else
  49546. triggerParams = ActionManager[trigger.name];
  49547. for (var j = 0; j < trigger.children.length; j++) {
  49548. if (!trigger.detached)
  49549. traverse(trigger.children[j], triggerParams, null, null);
  49550. }
  49551. }
  49552. };
  49553. ActionManager.GetTriggerName = function (trigger) {
  49554. switch (trigger) {
  49555. case 0: return "NothingTrigger";
  49556. case 1: return "OnPickTrigger";
  49557. case 2: return "OnLeftPickTrigger";
  49558. case 3: return "OnRightPickTrigger";
  49559. case 4: return "OnCenterPickTrigger";
  49560. case 5: return "OnPickDownTrigger";
  49561. case 6: return "OnPickUpTrigger";
  49562. case 7: return "OnLongPressTrigger";
  49563. case 8: return "OnPointerOverTrigger";
  49564. case 9: return "OnPointerOutTrigger";
  49565. case 10: return "OnEveryFrameTrigger";
  49566. case 11: return "OnIntersectionEnterTrigger";
  49567. case 12: return "OnIntersectionExitTrigger";
  49568. case 13: return "OnKeyDownTrigger";
  49569. case 14: return "OnKeyUpTrigger";
  49570. case 15: return "OnPickOutTrigger";
  49571. default: return "";
  49572. }
  49573. };
  49574. // Statics
  49575. ActionManager._NothingTrigger = 0;
  49576. ActionManager._OnPickTrigger = 1;
  49577. ActionManager._OnLeftPickTrigger = 2;
  49578. ActionManager._OnRightPickTrigger = 3;
  49579. ActionManager._OnCenterPickTrigger = 4;
  49580. ActionManager._OnPickDownTrigger = 5;
  49581. ActionManager._OnDoublePickTrigger = 6;
  49582. ActionManager._OnPickUpTrigger = 7;
  49583. ActionManager._OnLongPressTrigger = 8;
  49584. ActionManager._OnPointerOverTrigger = 9;
  49585. ActionManager._OnPointerOutTrigger = 10;
  49586. ActionManager._OnEveryFrameTrigger = 11;
  49587. ActionManager._OnIntersectionEnterTrigger = 12;
  49588. ActionManager._OnIntersectionExitTrigger = 13;
  49589. ActionManager._OnKeyDownTrigger = 14;
  49590. ActionManager._OnKeyUpTrigger = 15;
  49591. ActionManager._OnPickOutTrigger = 16;
  49592. ActionManager.Triggers = {};
  49593. return ActionManager;
  49594. }());
  49595. BABYLON.ActionManager = ActionManager;
  49596. })(BABYLON || (BABYLON = {}));
  49597. //# sourceMappingURL=babylon.actionManager.js.map
  49598. "use strict";
  49599. var BABYLON;
  49600. (function (BABYLON) {
  49601. var InterpolateValueAction = /** @class */ (function (_super) {
  49602. __extends(InterpolateValueAction, _super);
  49603. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  49604. if (duration === void 0) { duration = 1000; }
  49605. var _this = _super.call(this, triggerOptions, condition) || this;
  49606. _this.propertyPath = propertyPath;
  49607. _this.value = value;
  49608. _this.duration = duration;
  49609. _this.stopOtherAnimations = stopOtherAnimations;
  49610. _this.onInterpolationDone = onInterpolationDone;
  49611. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  49612. _this._target = _this._effectiveTarget = target;
  49613. return _this;
  49614. }
  49615. InterpolateValueAction.prototype._prepare = function () {
  49616. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49617. this._property = this._getProperty(this.propertyPath);
  49618. };
  49619. InterpolateValueAction.prototype.execute = function () {
  49620. var _this = this;
  49621. var scene = this._actionManager.getScene();
  49622. var keys = [
  49623. {
  49624. frame: 0,
  49625. value: this._effectiveTarget[this._property]
  49626. }, {
  49627. frame: 100,
  49628. value: this.value
  49629. }
  49630. ];
  49631. var dataType;
  49632. if (typeof this.value === "number") {
  49633. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  49634. }
  49635. else if (this.value instanceof BABYLON.Color3) {
  49636. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  49637. }
  49638. else if (this.value instanceof BABYLON.Vector3) {
  49639. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  49640. }
  49641. else if (this.value instanceof BABYLON.Matrix) {
  49642. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  49643. }
  49644. else if (this.value instanceof BABYLON.Quaternion) {
  49645. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  49646. }
  49647. else {
  49648. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  49649. return;
  49650. }
  49651. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  49652. animation.setKeys(keys);
  49653. if (this.stopOtherAnimations) {
  49654. scene.stopAnimation(this._effectiveTarget);
  49655. }
  49656. var wrapper = function () {
  49657. _this.onInterpolationDoneObservable.notifyObservers(_this);
  49658. if (_this.onInterpolationDone) {
  49659. _this.onInterpolationDone();
  49660. }
  49661. };
  49662. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  49663. };
  49664. InterpolateValueAction.prototype.serialize = function (parent) {
  49665. return _super.prototype._serialize.call(this, {
  49666. name: "InterpolateValueAction",
  49667. properties: [
  49668. BABYLON.Action._GetTargetProperty(this._target),
  49669. { name: "propertyPath", value: this.propertyPath },
  49670. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  49671. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  49672. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  49673. ]
  49674. }, parent);
  49675. };
  49676. return InterpolateValueAction;
  49677. }(BABYLON.Action));
  49678. BABYLON.InterpolateValueAction = InterpolateValueAction;
  49679. })(BABYLON || (BABYLON = {}));
  49680. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  49681. "use strict";
  49682. var BABYLON;
  49683. (function (BABYLON) {
  49684. var SwitchBooleanAction = /** @class */ (function (_super) {
  49685. __extends(SwitchBooleanAction, _super);
  49686. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  49687. var _this = _super.call(this, triggerOptions, condition) || this;
  49688. _this.propertyPath = propertyPath;
  49689. _this._target = _this._effectiveTarget = target;
  49690. return _this;
  49691. }
  49692. SwitchBooleanAction.prototype._prepare = function () {
  49693. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49694. this._property = this._getProperty(this.propertyPath);
  49695. };
  49696. SwitchBooleanAction.prototype.execute = function () {
  49697. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  49698. };
  49699. SwitchBooleanAction.prototype.serialize = function (parent) {
  49700. return _super.prototype._serialize.call(this, {
  49701. name: "SwitchBooleanAction",
  49702. properties: [
  49703. BABYLON.Action._GetTargetProperty(this._target),
  49704. { name: "propertyPath", value: this.propertyPath }
  49705. ]
  49706. }, parent);
  49707. };
  49708. return SwitchBooleanAction;
  49709. }(BABYLON.Action));
  49710. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  49711. var SetStateAction = /** @class */ (function (_super) {
  49712. __extends(SetStateAction, _super);
  49713. function SetStateAction(triggerOptions, target, value, condition) {
  49714. var _this = _super.call(this, triggerOptions, condition) || this;
  49715. _this.value = value;
  49716. _this._target = target;
  49717. return _this;
  49718. }
  49719. SetStateAction.prototype.execute = function () {
  49720. this._target.state = this.value;
  49721. };
  49722. SetStateAction.prototype.serialize = function (parent) {
  49723. return _super.prototype._serialize.call(this, {
  49724. name: "SetStateAction",
  49725. properties: [
  49726. BABYLON.Action._GetTargetProperty(this._target),
  49727. { name: "value", value: this.value }
  49728. ]
  49729. }, parent);
  49730. };
  49731. return SetStateAction;
  49732. }(BABYLON.Action));
  49733. BABYLON.SetStateAction = SetStateAction;
  49734. var SetValueAction = /** @class */ (function (_super) {
  49735. __extends(SetValueAction, _super);
  49736. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  49737. var _this = _super.call(this, triggerOptions, condition) || this;
  49738. _this.propertyPath = propertyPath;
  49739. _this.value = value;
  49740. _this._target = _this._effectiveTarget = target;
  49741. return _this;
  49742. }
  49743. SetValueAction.prototype._prepare = function () {
  49744. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49745. this._property = this._getProperty(this.propertyPath);
  49746. };
  49747. SetValueAction.prototype.execute = function () {
  49748. this._effectiveTarget[this._property] = this.value;
  49749. if (this._target.markAsDirty) {
  49750. this._target.markAsDirty(this._property);
  49751. }
  49752. };
  49753. SetValueAction.prototype.serialize = function (parent) {
  49754. return _super.prototype._serialize.call(this, {
  49755. name: "SetValueAction",
  49756. properties: [
  49757. BABYLON.Action._GetTargetProperty(this._target),
  49758. { name: "propertyPath", value: this.propertyPath },
  49759. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49760. ]
  49761. }, parent);
  49762. };
  49763. return SetValueAction;
  49764. }(BABYLON.Action));
  49765. BABYLON.SetValueAction = SetValueAction;
  49766. var IncrementValueAction = /** @class */ (function (_super) {
  49767. __extends(IncrementValueAction, _super);
  49768. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  49769. var _this = _super.call(this, triggerOptions, condition) || this;
  49770. _this.propertyPath = propertyPath;
  49771. _this.value = value;
  49772. _this._target = _this._effectiveTarget = target;
  49773. return _this;
  49774. }
  49775. IncrementValueAction.prototype._prepare = function () {
  49776. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49777. this._property = this._getProperty(this.propertyPath);
  49778. if (typeof this._effectiveTarget[this._property] !== "number") {
  49779. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  49780. }
  49781. };
  49782. IncrementValueAction.prototype.execute = function () {
  49783. this._effectiveTarget[this._property] += this.value;
  49784. if (this._target.markAsDirty) {
  49785. this._target.markAsDirty(this._property);
  49786. }
  49787. };
  49788. IncrementValueAction.prototype.serialize = function (parent) {
  49789. return _super.prototype._serialize.call(this, {
  49790. name: "IncrementValueAction",
  49791. properties: [
  49792. BABYLON.Action._GetTargetProperty(this._target),
  49793. { name: "propertyPath", value: this.propertyPath },
  49794. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49795. ]
  49796. }, parent);
  49797. };
  49798. return IncrementValueAction;
  49799. }(BABYLON.Action));
  49800. BABYLON.IncrementValueAction = IncrementValueAction;
  49801. var PlayAnimationAction = /** @class */ (function (_super) {
  49802. __extends(PlayAnimationAction, _super);
  49803. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  49804. var _this = _super.call(this, triggerOptions, condition) || this;
  49805. _this.from = from;
  49806. _this.to = to;
  49807. _this.loop = loop;
  49808. _this._target = target;
  49809. return _this;
  49810. }
  49811. PlayAnimationAction.prototype._prepare = function () {
  49812. };
  49813. PlayAnimationAction.prototype.execute = function () {
  49814. var scene = this._actionManager.getScene();
  49815. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  49816. };
  49817. PlayAnimationAction.prototype.serialize = function (parent) {
  49818. return _super.prototype._serialize.call(this, {
  49819. name: "PlayAnimationAction",
  49820. properties: [
  49821. BABYLON.Action._GetTargetProperty(this._target),
  49822. { name: "from", value: String(this.from) },
  49823. { name: "to", value: String(this.to) },
  49824. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  49825. ]
  49826. }, parent);
  49827. };
  49828. return PlayAnimationAction;
  49829. }(BABYLON.Action));
  49830. BABYLON.PlayAnimationAction = PlayAnimationAction;
  49831. var StopAnimationAction = /** @class */ (function (_super) {
  49832. __extends(StopAnimationAction, _super);
  49833. function StopAnimationAction(triggerOptions, target, condition) {
  49834. var _this = _super.call(this, triggerOptions, condition) || this;
  49835. _this._target = target;
  49836. return _this;
  49837. }
  49838. StopAnimationAction.prototype._prepare = function () {
  49839. };
  49840. StopAnimationAction.prototype.execute = function () {
  49841. var scene = this._actionManager.getScene();
  49842. scene.stopAnimation(this._target);
  49843. };
  49844. StopAnimationAction.prototype.serialize = function (parent) {
  49845. return _super.prototype._serialize.call(this, {
  49846. name: "StopAnimationAction",
  49847. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  49848. }, parent);
  49849. };
  49850. return StopAnimationAction;
  49851. }(BABYLON.Action));
  49852. BABYLON.StopAnimationAction = StopAnimationAction;
  49853. var DoNothingAction = /** @class */ (function (_super) {
  49854. __extends(DoNothingAction, _super);
  49855. function DoNothingAction(triggerOptions, condition) {
  49856. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  49857. return _super.call(this, triggerOptions, condition) || this;
  49858. }
  49859. DoNothingAction.prototype.execute = function () {
  49860. };
  49861. DoNothingAction.prototype.serialize = function (parent) {
  49862. return _super.prototype._serialize.call(this, {
  49863. name: "DoNothingAction",
  49864. properties: []
  49865. }, parent);
  49866. };
  49867. return DoNothingAction;
  49868. }(BABYLON.Action));
  49869. BABYLON.DoNothingAction = DoNothingAction;
  49870. var CombineAction = /** @class */ (function (_super) {
  49871. __extends(CombineAction, _super);
  49872. function CombineAction(triggerOptions, children, condition) {
  49873. var _this = _super.call(this, triggerOptions, condition) || this;
  49874. _this.children = children;
  49875. return _this;
  49876. }
  49877. CombineAction.prototype._prepare = function () {
  49878. for (var index = 0; index < this.children.length; index++) {
  49879. this.children[index]._actionManager = this._actionManager;
  49880. this.children[index]._prepare();
  49881. }
  49882. };
  49883. CombineAction.prototype.execute = function (evt) {
  49884. for (var index = 0; index < this.children.length; index++) {
  49885. this.children[index].execute(evt);
  49886. }
  49887. };
  49888. CombineAction.prototype.serialize = function (parent) {
  49889. var serializationObject = _super.prototype._serialize.call(this, {
  49890. name: "CombineAction",
  49891. properties: [],
  49892. combine: []
  49893. }, parent);
  49894. for (var i = 0; i < this.children.length; i++) {
  49895. serializationObject.combine.push(this.children[i].serialize(null));
  49896. }
  49897. return serializationObject;
  49898. };
  49899. return CombineAction;
  49900. }(BABYLON.Action));
  49901. BABYLON.CombineAction = CombineAction;
  49902. var ExecuteCodeAction = /** @class */ (function (_super) {
  49903. __extends(ExecuteCodeAction, _super);
  49904. function ExecuteCodeAction(triggerOptions, func, condition) {
  49905. var _this = _super.call(this, triggerOptions, condition) || this;
  49906. _this.func = func;
  49907. return _this;
  49908. }
  49909. ExecuteCodeAction.prototype.execute = function (evt) {
  49910. this.func(evt);
  49911. };
  49912. return ExecuteCodeAction;
  49913. }(BABYLON.Action));
  49914. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  49915. var SetParentAction = /** @class */ (function (_super) {
  49916. __extends(SetParentAction, _super);
  49917. function SetParentAction(triggerOptions, target, parent, condition) {
  49918. var _this = _super.call(this, triggerOptions, condition) || this;
  49919. _this._target = target;
  49920. _this._parent = parent;
  49921. return _this;
  49922. }
  49923. SetParentAction.prototype._prepare = function () {
  49924. };
  49925. SetParentAction.prototype.execute = function () {
  49926. if (this._target.parent === this._parent) {
  49927. return;
  49928. }
  49929. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  49930. invertParentWorldMatrix.invert();
  49931. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  49932. this._target.parent = this._parent;
  49933. };
  49934. SetParentAction.prototype.serialize = function (parent) {
  49935. return _super.prototype._serialize.call(this, {
  49936. name: "SetParentAction",
  49937. properties: [
  49938. BABYLON.Action._GetTargetProperty(this._target),
  49939. BABYLON.Action._GetTargetProperty(this._parent),
  49940. ]
  49941. }, parent);
  49942. };
  49943. return SetParentAction;
  49944. }(BABYLON.Action));
  49945. BABYLON.SetParentAction = SetParentAction;
  49946. var PlaySoundAction = /** @class */ (function (_super) {
  49947. __extends(PlaySoundAction, _super);
  49948. function PlaySoundAction(triggerOptions, sound, condition) {
  49949. var _this = _super.call(this, triggerOptions, condition) || this;
  49950. _this._sound = sound;
  49951. return _this;
  49952. }
  49953. PlaySoundAction.prototype._prepare = function () {
  49954. };
  49955. PlaySoundAction.prototype.execute = function () {
  49956. if (this._sound !== undefined)
  49957. this._sound.play();
  49958. };
  49959. PlaySoundAction.prototype.serialize = function (parent) {
  49960. return _super.prototype._serialize.call(this, {
  49961. name: "PlaySoundAction",
  49962. properties: [{ name: "sound", value: this._sound.name }]
  49963. }, parent);
  49964. };
  49965. return PlaySoundAction;
  49966. }(BABYLON.Action));
  49967. BABYLON.PlaySoundAction = PlaySoundAction;
  49968. var StopSoundAction = /** @class */ (function (_super) {
  49969. __extends(StopSoundAction, _super);
  49970. function StopSoundAction(triggerOptions, sound, condition) {
  49971. var _this = _super.call(this, triggerOptions, condition) || this;
  49972. _this._sound = sound;
  49973. return _this;
  49974. }
  49975. StopSoundAction.prototype._prepare = function () {
  49976. };
  49977. StopSoundAction.prototype.execute = function () {
  49978. if (this._sound !== undefined)
  49979. this._sound.stop();
  49980. };
  49981. StopSoundAction.prototype.serialize = function (parent) {
  49982. return _super.prototype._serialize.call(this, {
  49983. name: "StopSoundAction",
  49984. properties: [{ name: "sound", value: this._sound.name }]
  49985. }, parent);
  49986. };
  49987. return StopSoundAction;
  49988. }(BABYLON.Action));
  49989. BABYLON.StopSoundAction = StopSoundAction;
  49990. })(BABYLON || (BABYLON = {}));
  49991. //# sourceMappingURL=babylon.directActions.js.map
  49992. "use strict";
  49993. var BABYLON;
  49994. (function (BABYLON) {
  49995. var SpriteManager = /** @class */ (function () {
  49996. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  49997. if (epsilon === void 0) { epsilon = 0.01; }
  49998. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49999. this.name = name;
  50000. this.sprites = new Array();
  50001. this.renderingGroupId = 0;
  50002. this.layerMask = 0x0FFFFFFF;
  50003. this.fogEnabled = true;
  50004. this.isPickable = false;
  50005. /**
  50006. * An event triggered when the manager is disposed.
  50007. * @type {BABYLON.Observable}
  50008. */
  50009. this.onDisposeObservable = new BABYLON.Observable();
  50010. this._vertexBuffers = {};
  50011. this._capacity = capacity;
  50012. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  50013. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50014. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50015. if (cellSize.width && cellSize.height) {
  50016. this.cellWidth = cellSize.width;
  50017. this.cellHeight = cellSize.height;
  50018. }
  50019. else if (cellSize !== undefined) {
  50020. this.cellWidth = cellSize;
  50021. this.cellHeight = cellSize;
  50022. }
  50023. else {
  50024. return;
  50025. }
  50026. this._epsilon = epsilon;
  50027. this._scene = scene;
  50028. this._scene.spriteManagers.push(this);
  50029. var indices = [];
  50030. var index = 0;
  50031. for (var count = 0; count < capacity; count++) {
  50032. indices.push(index);
  50033. indices.push(index + 1);
  50034. indices.push(index + 2);
  50035. indices.push(index);
  50036. indices.push(index + 2);
  50037. indices.push(index + 3);
  50038. index += 4;
  50039. }
  50040. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  50041. // VBO
  50042. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  50043. this._vertexData = new Float32Array(capacity * 16 * 4);
  50044. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  50045. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  50046. var options = this._buffer.createVertexBuffer("options", 4, 4);
  50047. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  50048. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  50049. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50050. this._vertexBuffers["options"] = options;
  50051. this._vertexBuffers["cellInfo"] = cellInfo;
  50052. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50053. // Effects
  50054. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  50055. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  50056. }
  50057. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  50058. set: function (callback) {
  50059. if (this._onDisposeObserver) {
  50060. this.onDisposeObservable.remove(this._onDisposeObserver);
  50061. }
  50062. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50063. },
  50064. enumerable: true,
  50065. configurable: true
  50066. });
  50067. Object.defineProperty(SpriteManager.prototype, "texture", {
  50068. get: function () {
  50069. return this._spriteTexture;
  50070. },
  50071. set: function (value) {
  50072. this._spriteTexture = value;
  50073. },
  50074. enumerable: true,
  50075. configurable: true
  50076. });
  50077. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  50078. var arrayOffset = index * 16;
  50079. if (offsetX === 0)
  50080. offsetX = this._epsilon;
  50081. else if (offsetX === 1)
  50082. offsetX = 1 - this._epsilon;
  50083. if (offsetY === 0)
  50084. offsetY = this._epsilon;
  50085. else if (offsetY === 1)
  50086. offsetY = 1 - this._epsilon;
  50087. this._vertexData[arrayOffset] = sprite.position.x;
  50088. this._vertexData[arrayOffset + 1] = sprite.position.y;
  50089. this._vertexData[arrayOffset + 2] = sprite.position.z;
  50090. this._vertexData[arrayOffset + 3] = sprite.angle;
  50091. this._vertexData[arrayOffset + 4] = sprite.width;
  50092. this._vertexData[arrayOffset + 5] = sprite.height;
  50093. this._vertexData[arrayOffset + 6] = offsetX;
  50094. this._vertexData[arrayOffset + 7] = offsetY;
  50095. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  50096. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  50097. var offset = (sprite.cellIndex / rowSize) >> 0;
  50098. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  50099. this._vertexData[arrayOffset + 11] = offset;
  50100. // Color
  50101. this._vertexData[arrayOffset + 12] = sprite.color.r;
  50102. this._vertexData[arrayOffset + 13] = sprite.color.g;
  50103. this._vertexData[arrayOffset + 14] = sprite.color.b;
  50104. this._vertexData[arrayOffset + 15] = sprite.color.a;
  50105. };
  50106. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  50107. var count = Math.min(this._capacity, this.sprites.length);
  50108. var min = BABYLON.Vector3.Zero();
  50109. var max = BABYLON.Vector3.Zero();
  50110. var distance = Number.MAX_VALUE;
  50111. var currentSprite = null;
  50112. var cameraSpacePosition = BABYLON.Vector3.Zero();
  50113. var cameraView = camera.getViewMatrix();
  50114. for (var index = 0; index < count; index++) {
  50115. var sprite = this.sprites[index];
  50116. if (!sprite) {
  50117. continue;
  50118. }
  50119. if (predicate) {
  50120. if (!predicate(sprite)) {
  50121. continue;
  50122. }
  50123. }
  50124. else if (!sprite.isPickable) {
  50125. continue;
  50126. }
  50127. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  50128. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  50129. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  50130. if (ray.intersectsBoxMinMax(min, max)) {
  50131. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  50132. if (distance > currentDistance) {
  50133. distance = currentDistance;
  50134. currentSprite = sprite;
  50135. if (fastCheck) {
  50136. break;
  50137. }
  50138. }
  50139. }
  50140. }
  50141. if (currentSprite) {
  50142. var result = new BABYLON.PickingInfo();
  50143. result.hit = true;
  50144. result.pickedSprite = currentSprite;
  50145. result.distance = distance;
  50146. return result;
  50147. }
  50148. return null;
  50149. };
  50150. SpriteManager.prototype.render = function () {
  50151. // Check
  50152. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  50153. return;
  50154. var engine = this._scene.getEngine();
  50155. var baseSize = this._spriteTexture.getBaseSize();
  50156. // Sprites
  50157. var deltaTime = engine.getDeltaTime();
  50158. var max = Math.min(this._capacity, this.sprites.length);
  50159. var rowSize = baseSize.width / this.cellWidth;
  50160. var offset = 0;
  50161. for (var index = 0; index < max; index++) {
  50162. var sprite = this.sprites[index];
  50163. if (!sprite) {
  50164. continue;
  50165. }
  50166. sprite._animate(deltaTime);
  50167. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  50168. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  50169. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  50170. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  50171. }
  50172. this._buffer.update(this._vertexData);
  50173. // Render
  50174. var effect = this._effectBase;
  50175. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50176. effect = this._effectFog;
  50177. }
  50178. engine.enableEffect(effect);
  50179. var viewMatrix = this._scene.getViewMatrix();
  50180. effect.setTexture("diffuseSampler", this._spriteTexture);
  50181. effect.setMatrix("view", viewMatrix);
  50182. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  50183. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  50184. // Fog
  50185. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50186. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  50187. effect.setColor3("vFogColor", this._scene.fogColor);
  50188. }
  50189. // VBOs
  50190. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  50191. // Draw order
  50192. engine.setDepthFunctionToLessOrEqual();
  50193. effect.setBool("alphaTest", true);
  50194. engine.setColorWrite(false);
  50195. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  50196. engine.setColorWrite(true);
  50197. effect.setBool("alphaTest", false);
  50198. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50199. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  50200. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50201. };
  50202. SpriteManager.prototype.dispose = function () {
  50203. if (this._buffer) {
  50204. this._buffer.dispose();
  50205. this._buffer = null;
  50206. }
  50207. if (this._indexBuffer) {
  50208. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50209. this._indexBuffer = null;
  50210. }
  50211. if (this._spriteTexture) {
  50212. this._spriteTexture.dispose();
  50213. this._spriteTexture = null;
  50214. }
  50215. // Remove from scene
  50216. var index = this._scene.spriteManagers.indexOf(this);
  50217. this._scene.spriteManagers.splice(index, 1);
  50218. // Callback
  50219. this.onDisposeObservable.notifyObservers(this);
  50220. this.onDisposeObservable.clear();
  50221. };
  50222. return SpriteManager;
  50223. }());
  50224. BABYLON.SpriteManager = SpriteManager;
  50225. })(BABYLON || (BABYLON = {}));
  50226. //# sourceMappingURL=babylon.spriteManager.js.map
  50227. "use strict";
  50228. var BABYLON;
  50229. (function (BABYLON) {
  50230. var Sprite = /** @class */ (function () {
  50231. function Sprite(name, manager) {
  50232. this.name = name;
  50233. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50234. this.width = 1.0;
  50235. this.height = 1.0;
  50236. this.angle = 0;
  50237. this.cellIndex = 0;
  50238. this.invertU = 0;
  50239. this.invertV = 0;
  50240. this.animations = new Array();
  50241. this.isPickable = false;
  50242. this._animationStarted = false;
  50243. this._loopAnimation = false;
  50244. this._fromIndex = 0;
  50245. this._toIndex = 0;
  50246. this._delay = 0;
  50247. this._direction = 1;
  50248. this._time = 0;
  50249. this._manager = manager;
  50250. this._manager.sprites.push(this);
  50251. this.position = BABYLON.Vector3.Zero();
  50252. }
  50253. Object.defineProperty(Sprite.prototype, "size", {
  50254. get: function () {
  50255. return this.width;
  50256. },
  50257. set: function (value) {
  50258. this.width = value;
  50259. this.height = value;
  50260. },
  50261. enumerable: true,
  50262. configurable: true
  50263. });
  50264. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  50265. this._fromIndex = from;
  50266. this._toIndex = to;
  50267. this._loopAnimation = loop;
  50268. this._delay = delay;
  50269. this._animationStarted = true;
  50270. this._direction = from < to ? 1 : -1;
  50271. this.cellIndex = from;
  50272. this._time = 0;
  50273. this._onAnimationEnd = onAnimationEnd;
  50274. };
  50275. Sprite.prototype.stopAnimation = function () {
  50276. this._animationStarted = false;
  50277. };
  50278. Sprite.prototype._animate = function (deltaTime) {
  50279. if (!this._animationStarted)
  50280. return;
  50281. this._time += deltaTime;
  50282. if (this._time > this._delay) {
  50283. this._time = this._time % this._delay;
  50284. this.cellIndex += this._direction;
  50285. if (this.cellIndex > this._toIndex) {
  50286. if (this._loopAnimation) {
  50287. this.cellIndex = this._fromIndex;
  50288. }
  50289. else {
  50290. this.cellIndex = this._toIndex;
  50291. this._animationStarted = false;
  50292. if (this._onAnimationEnd) {
  50293. this._onAnimationEnd();
  50294. }
  50295. if (this.disposeWhenFinishedAnimating) {
  50296. this.dispose();
  50297. }
  50298. }
  50299. }
  50300. }
  50301. };
  50302. Sprite.prototype.dispose = function () {
  50303. for (var i = 0; i < this._manager.sprites.length; i++) {
  50304. if (this._manager.sprites[i] == this) {
  50305. this._manager.sprites.splice(i, 1);
  50306. }
  50307. }
  50308. };
  50309. return Sprite;
  50310. }());
  50311. BABYLON.Sprite = Sprite;
  50312. })(BABYLON || (BABYLON = {}));
  50313. //# sourceMappingURL=babylon.sprite.js.map
  50314. "use strict";
  50315. var BABYLON;
  50316. (function (BABYLON) {
  50317. var IntersectionInfo = /** @class */ (function () {
  50318. function IntersectionInfo(bu, bv, distance) {
  50319. this.bu = bu;
  50320. this.bv = bv;
  50321. this.distance = distance;
  50322. this.faceId = 0;
  50323. this.subMeshId = 0;
  50324. }
  50325. return IntersectionInfo;
  50326. }());
  50327. BABYLON.IntersectionInfo = IntersectionInfo;
  50328. var PickingInfo = /** @class */ (function () {
  50329. function PickingInfo() {
  50330. this.hit = false;
  50331. this.distance = 0;
  50332. this.pickedPoint = null;
  50333. this.pickedMesh = null;
  50334. this.bu = 0;
  50335. this.bv = 0;
  50336. this.faceId = -1;
  50337. this.subMeshId = 0;
  50338. this.pickedSprite = null;
  50339. }
  50340. // Methods
  50341. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  50342. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  50343. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  50344. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  50345. return null;
  50346. }
  50347. var indices = this.pickedMesh.getIndices();
  50348. if (!indices) {
  50349. return null;
  50350. }
  50351. var result;
  50352. if (useVerticesNormals) {
  50353. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50354. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  50355. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  50356. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  50357. normal0 = normal0.scale(this.bu);
  50358. normal1 = normal1.scale(this.bv);
  50359. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  50360. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  50361. }
  50362. else {
  50363. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50364. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  50365. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  50366. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  50367. var p1p2 = vertex1.subtract(vertex2);
  50368. var p3p2 = vertex3.subtract(vertex2);
  50369. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  50370. }
  50371. if (useWorldCoordinates) {
  50372. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  50373. }
  50374. return BABYLON.Vector3.Normalize(result);
  50375. };
  50376. PickingInfo.prototype.getTextureCoordinates = function () {
  50377. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50378. return null;
  50379. }
  50380. var indices = this.pickedMesh.getIndices();
  50381. if (!indices) {
  50382. return null;
  50383. }
  50384. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50385. if (!uvs) {
  50386. return null;
  50387. }
  50388. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  50389. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  50390. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  50391. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  50392. uv1 = uv1.scale(this.bu);
  50393. uv2 = uv2.scale(this.bv);
  50394. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  50395. };
  50396. return PickingInfo;
  50397. }());
  50398. BABYLON.PickingInfo = PickingInfo;
  50399. })(BABYLON || (BABYLON = {}));
  50400. //# sourceMappingURL=babylon.pickingInfo.js.map
  50401. "use strict";
  50402. var BABYLON;
  50403. (function (BABYLON) {
  50404. var Ray = /** @class */ (function () {
  50405. function Ray(origin, direction, length) {
  50406. if (length === void 0) { length = Number.MAX_VALUE; }
  50407. this.origin = origin;
  50408. this.direction = direction;
  50409. this.length = length;
  50410. }
  50411. // Methods
  50412. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  50413. var d = 0.0;
  50414. var maxValue = Number.MAX_VALUE;
  50415. var inv;
  50416. var min;
  50417. var max;
  50418. var temp;
  50419. if (Math.abs(this.direction.x) < 0.0000001) {
  50420. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  50421. return false;
  50422. }
  50423. }
  50424. else {
  50425. inv = 1.0 / this.direction.x;
  50426. min = (minimum.x - this.origin.x) * inv;
  50427. max = (maximum.x - this.origin.x) * inv;
  50428. if (max === -Infinity) {
  50429. max = Infinity;
  50430. }
  50431. if (min > max) {
  50432. temp = min;
  50433. min = max;
  50434. max = temp;
  50435. }
  50436. d = Math.max(min, d);
  50437. maxValue = Math.min(max, maxValue);
  50438. if (d > maxValue) {
  50439. return false;
  50440. }
  50441. }
  50442. if (Math.abs(this.direction.y) < 0.0000001) {
  50443. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  50444. return false;
  50445. }
  50446. }
  50447. else {
  50448. inv = 1.0 / this.direction.y;
  50449. min = (minimum.y - this.origin.y) * inv;
  50450. max = (maximum.y - this.origin.y) * inv;
  50451. if (max === -Infinity) {
  50452. max = Infinity;
  50453. }
  50454. if (min > max) {
  50455. temp = min;
  50456. min = max;
  50457. max = temp;
  50458. }
  50459. d = Math.max(min, d);
  50460. maxValue = Math.min(max, maxValue);
  50461. if (d > maxValue) {
  50462. return false;
  50463. }
  50464. }
  50465. if (Math.abs(this.direction.z) < 0.0000001) {
  50466. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  50467. return false;
  50468. }
  50469. }
  50470. else {
  50471. inv = 1.0 / this.direction.z;
  50472. min = (minimum.z - this.origin.z) * inv;
  50473. max = (maximum.z - this.origin.z) * inv;
  50474. if (max === -Infinity) {
  50475. max = Infinity;
  50476. }
  50477. if (min > max) {
  50478. temp = min;
  50479. min = max;
  50480. max = temp;
  50481. }
  50482. d = Math.max(min, d);
  50483. maxValue = Math.min(max, maxValue);
  50484. if (d > maxValue) {
  50485. return false;
  50486. }
  50487. }
  50488. return true;
  50489. };
  50490. Ray.prototype.intersectsBox = function (box) {
  50491. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  50492. };
  50493. Ray.prototype.intersectsSphere = function (sphere) {
  50494. var x = sphere.center.x - this.origin.x;
  50495. var y = sphere.center.y - this.origin.y;
  50496. var z = sphere.center.z - this.origin.z;
  50497. var pyth = (x * x) + (y * y) + (z * z);
  50498. var rr = sphere.radius * sphere.radius;
  50499. if (pyth <= rr) {
  50500. return true;
  50501. }
  50502. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  50503. if (dot < 0.0) {
  50504. return false;
  50505. }
  50506. var temp = pyth - (dot * dot);
  50507. return temp <= rr;
  50508. };
  50509. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  50510. if (!this._edge1) {
  50511. this._edge1 = BABYLON.Vector3.Zero();
  50512. this._edge2 = BABYLON.Vector3.Zero();
  50513. this._pvec = BABYLON.Vector3.Zero();
  50514. this._tvec = BABYLON.Vector3.Zero();
  50515. this._qvec = BABYLON.Vector3.Zero();
  50516. }
  50517. vertex1.subtractToRef(vertex0, this._edge1);
  50518. vertex2.subtractToRef(vertex0, this._edge2);
  50519. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  50520. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  50521. if (det === 0) {
  50522. return null;
  50523. }
  50524. var invdet = 1 / det;
  50525. this.origin.subtractToRef(vertex0, this._tvec);
  50526. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  50527. if (bu < 0 || bu > 1.0) {
  50528. return null;
  50529. }
  50530. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  50531. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  50532. if (bv < 0 || bu + bv > 1.0) {
  50533. return null;
  50534. }
  50535. //check if the distance is longer than the predefined length.
  50536. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  50537. if (distance > this.length) {
  50538. return null;
  50539. }
  50540. return new BABYLON.IntersectionInfo(bu, bv, distance);
  50541. };
  50542. Ray.prototype.intersectsPlane = function (plane) {
  50543. var distance;
  50544. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  50545. if (Math.abs(result1) < 9.99999997475243E-07) {
  50546. return null;
  50547. }
  50548. else {
  50549. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  50550. distance = (-plane.d - result2) / result1;
  50551. if (distance < 0.0) {
  50552. if (distance < -9.99999997475243E-07) {
  50553. return null;
  50554. }
  50555. else {
  50556. return 0;
  50557. }
  50558. }
  50559. return distance;
  50560. }
  50561. };
  50562. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  50563. var tm = BABYLON.Tmp.Matrix[0];
  50564. mesh.getWorldMatrix().invertToRef(tm);
  50565. if (this._tmpRay) {
  50566. Ray.TransformToRef(this, tm, this._tmpRay);
  50567. }
  50568. else {
  50569. this._tmpRay = Ray.Transform(this, tm);
  50570. }
  50571. return mesh.intersects(this._tmpRay, fastCheck);
  50572. };
  50573. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  50574. if (results) {
  50575. results.length = 0;
  50576. }
  50577. else {
  50578. results = [];
  50579. }
  50580. for (var i = 0; i < meshes.length; i++) {
  50581. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  50582. if (pickInfo.hit) {
  50583. results.push(pickInfo);
  50584. }
  50585. }
  50586. results.sort(this._comparePickingInfo);
  50587. return results;
  50588. };
  50589. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  50590. if (pickingInfoA.distance < pickingInfoB.distance) {
  50591. return -1;
  50592. }
  50593. else if (pickingInfoA.distance > pickingInfoB.distance) {
  50594. return 1;
  50595. }
  50596. else {
  50597. return 0;
  50598. }
  50599. };
  50600. /**
  50601. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  50602. * @param sega the first point of the segment to test the intersection against
  50603. * @param segb the second point of the segment to test the intersection against
  50604. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  50605. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  50606. */
  50607. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  50608. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  50609. var u = segb.subtract(sega);
  50610. var v = rsegb.subtract(this.origin);
  50611. var w = sega.subtract(this.origin);
  50612. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  50613. var b = BABYLON.Vector3.Dot(u, v);
  50614. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  50615. var d = BABYLON.Vector3.Dot(u, w);
  50616. var e = BABYLON.Vector3.Dot(v, w);
  50617. var D = a * c - b * b; // always >= 0
  50618. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  50619. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  50620. // compute the line parameters of the two closest points
  50621. if (D < Ray.smallnum) {
  50622. sN = 0.0; // force using point P0 on segment S1
  50623. sD = 1.0; // to prevent possible division by 0.0 later
  50624. tN = e;
  50625. tD = c;
  50626. }
  50627. else {
  50628. sN = (b * e - c * d);
  50629. tN = (a * e - b * d);
  50630. if (sN < 0.0) {
  50631. sN = 0.0;
  50632. tN = e;
  50633. tD = c;
  50634. }
  50635. else if (sN > sD) {
  50636. sN = sD;
  50637. tN = e + b;
  50638. tD = c;
  50639. }
  50640. }
  50641. if (tN < 0.0) {
  50642. tN = 0.0;
  50643. // recompute sc for this edge
  50644. if (-d < 0.0) {
  50645. sN = 0.0;
  50646. }
  50647. else if (-d > a)
  50648. sN = sD;
  50649. else {
  50650. sN = -d;
  50651. sD = a;
  50652. }
  50653. }
  50654. else if (tN > tD) {
  50655. tN = tD;
  50656. // recompute sc for this edge
  50657. if ((-d + b) < 0.0) {
  50658. sN = 0;
  50659. }
  50660. else if ((-d + b) > a) {
  50661. sN = sD;
  50662. }
  50663. else {
  50664. sN = (-d + b);
  50665. sD = a;
  50666. }
  50667. }
  50668. // finally do the division to get sc and tc
  50669. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  50670. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  50671. // get the difference of the two closest points
  50672. var qtc = v.multiplyByFloats(tc, tc, tc);
  50673. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  50674. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  50675. if (isIntersected) {
  50676. return qtc.length();
  50677. }
  50678. return -1;
  50679. };
  50680. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50681. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  50682. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  50683. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  50684. this.direction.normalize();
  50685. return this;
  50686. };
  50687. // Statics
  50688. Ray.Zero = function () {
  50689. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  50690. };
  50691. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50692. var result = Ray.Zero();
  50693. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  50694. };
  50695. /**
  50696. * 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
  50697. * transformed to the given world matrix.
  50698. * @param origin The origin point
  50699. * @param end The end point
  50700. * @param world a matrix to transform the ray to. Default is the identity matrix.
  50701. */
  50702. Ray.CreateNewFromTo = function (origin, end, world) {
  50703. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  50704. var direction = end.subtract(origin);
  50705. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  50706. direction.normalize();
  50707. return Ray.Transform(new Ray(origin, direction, length), world);
  50708. };
  50709. Ray.Transform = function (ray, matrix) {
  50710. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  50711. Ray.TransformToRef(ray, matrix, result);
  50712. return result;
  50713. };
  50714. Ray.TransformToRef = function (ray, matrix, result) {
  50715. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  50716. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  50717. result.length = ray.length;
  50718. var dir = result.direction;
  50719. var len = dir.length();
  50720. if (!(len === 0 || len === 1)) {
  50721. var num = 1.0 / len;
  50722. dir.x *= num;
  50723. dir.y *= num;
  50724. dir.z *= num;
  50725. result.length *= len;
  50726. }
  50727. };
  50728. Ray.smallnum = 0.00000001;
  50729. Ray.rayl = 10e8;
  50730. return Ray;
  50731. }());
  50732. BABYLON.Ray = Ray;
  50733. })(BABYLON || (BABYLON = {}));
  50734. //# sourceMappingURL=babylon.ray.js.map
  50735. "use strict";
  50736. var BABYLON;
  50737. (function (BABYLON) {
  50738. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  50739. if (boxMin.x > sphereCenter.x + sphereRadius)
  50740. return false;
  50741. if (sphereCenter.x - sphereRadius > boxMax.x)
  50742. return false;
  50743. if (boxMin.y > sphereCenter.y + sphereRadius)
  50744. return false;
  50745. if (sphereCenter.y - sphereRadius > boxMax.y)
  50746. return false;
  50747. if (boxMin.z > sphereCenter.z + sphereRadius)
  50748. return false;
  50749. if (sphereCenter.z - sphereRadius > boxMax.z)
  50750. return false;
  50751. return true;
  50752. };
  50753. var getLowestRoot = (function () {
  50754. var result = { root: 0, found: false };
  50755. return function (a, b, c, maxR) {
  50756. result.root = 0;
  50757. result.found = false;
  50758. var determinant = b * b - 4.0 * a * c;
  50759. if (determinant < 0)
  50760. return result;
  50761. var sqrtD = Math.sqrt(determinant);
  50762. var r1 = (-b - sqrtD) / (2.0 * a);
  50763. var r2 = (-b + sqrtD) / (2.0 * a);
  50764. if (r1 > r2) {
  50765. var temp = r2;
  50766. r2 = r1;
  50767. r1 = temp;
  50768. }
  50769. if (r1 > 0 && r1 < maxR) {
  50770. result.root = r1;
  50771. result.found = true;
  50772. return result;
  50773. }
  50774. if (r2 > 0 && r2 < maxR) {
  50775. result.root = r2;
  50776. result.found = true;
  50777. return result;
  50778. }
  50779. return result;
  50780. };
  50781. })();
  50782. var Collider = /** @class */ (function () {
  50783. function Collider() {
  50784. this._collisionPoint = BABYLON.Vector3.Zero();
  50785. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  50786. this._tempVector = BABYLON.Vector3.Zero();
  50787. this._tempVector2 = BABYLON.Vector3.Zero();
  50788. this._tempVector3 = BABYLON.Vector3.Zero();
  50789. this._tempVector4 = BABYLON.Vector3.Zero();
  50790. this._edge = BABYLON.Vector3.Zero();
  50791. this._baseToVertex = BABYLON.Vector3.Zero();
  50792. this._destinationPoint = BABYLON.Vector3.Zero();
  50793. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  50794. this._displacementVector = BABYLON.Vector3.Zero();
  50795. this._radius = BABYLON.Vector3.One();
  50796. this._retry = 0;
  50797. this._basePointWorld = BABYLON.Vector3.Zero();
  50798. this._velocityWorld = BABYLON.Vector3.Zero();
  50799. this._normalizedVelocity = BABYLON.Vector3.Zero();
  50800. this._collisionMask = -1;
  50801. }
  50802. Object.defineProperty(Collider.prototype, "collisionMask", {
  50803. get: function () {
  50804. return this._collisionMask;
  50805. },
  50806. set: function (mask) {
  50807. this._collisionMask = !isNaN(mask) ? mask : -1;
  50808. },
  50809. enumerable: true,
  50810. configurable: true
  50811. });
  50812. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  50813. /**
  50814. * Gets the plane normal used to compute the sliding response (in local space)
  50815. */
  50816. get: function () {
  50817. return this._slidePlaneNormal;
  50818. },
  50819. enumerable: true,
  50820. configurable: true
  50821. });
  50822. // Methods
  50823. Collider.prototype._initialize = function (source, dir, e) {
  50824. this._velocity = dir;
  50825. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  50826. this._basePoint = source;
  50827. source.multiplyToRef(this._radius, this._basePointWorld);
  50828. dir.multiplyToRef(this._radius, this._velocityWorld);
  50829. this._velocityWorldLength = this._velocityWorld.length();
  50830. this._epsilon = e;
  50831. this.collisionFound = false;
  50832. };
  50833. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  50834. pa.subtractToRef(point, this._tempVector);
  50835. pb.subtractToRef(point, this._tempVector2);
  50836. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  50837. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50838. if (d < 0)
  50839. return false;
  50840. pc.subtractToRef(point, this._tempVector3);
  50841. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  50842. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50843. if (d < 0)
  50844. return false;
  50845. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  50846. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50847. return d >= 0;
  50848. };
  50849. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  50850. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  50851. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  50852. if (distance > this._velocityWorldLength + max + sphereRadius) {
  50853. return false;
  50854. }
  50855. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  50856. return false;
  50857. return true;
  50858. };
  50859. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  50860. var t0;
  50861. var embeddedInPlane = false;
  50862. //defensive programming, actually not needed.
  50863. if (!trianglePlaneArray) {
  50864. trianglePlaneArray = [];
  50865. }
  50866. if (!trianglePlaneArray[faceIndex]) {
  50867. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  50868. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  50869. }
  50870. var trianglePlane = trianglePlaneArray[faceIndex];
  50871. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  50872. return;
  50873. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  50874. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  50875. if (normalDotVelocity == 0) {
  50876. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  50877. return;
  50878. embeddedInPlane = true;
  50879. t0 = 0;
  50880. }
  50881. else {
  50882. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50883. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50884. if (t0 > t1) {
  50885. var temp = t1;
  50886. t1 = t0;
  50887. t0 = temp;
  50888. }
  50889. if (t0 > 1.0 || t1 < 0.0)
  50890. return;
  50891. if (t0 < 0)
  50892. t0 = 0;
  50893. if (t0 > 1.0)
  50894. t0 = 1.0;
  50895. }
  50896. this._collisionPoint.copyFromFloats(0, 0, 0);
  50897. var found = false;
  50898. var t = 1.0;
  50899. if (!embeddedInPlane) {
  50900. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  50901. this._velocity.scaleToRef(t0, this._tempVector);
  50902. this._planeIntersectionPoint.addInPlace(this._tempVector);
  50903. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  50904. found = true;
  50905. t = t0;
  50906. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  50907. }
  50908. }
  50909. if (!found) {
  50910. var velocitySquaredLength = this._velocity.lengthSquared();
  50911. var a = velocitySquaredLength;
  50912. this._basePoint.subtractToRef(p1, this._tempVector);
  50913. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50914. var c = this._tempVector.lengthSquared() - 1.0;
  50915. var lowestRoot = getLowestRoot(a, b, c, t);
  50916. if (lowestRoot.found) {
  50917. t = lowestRoot.root;
  50918. found = true;
  50919. this._collisionPoint.copyFrom(p1);
  50920. }
  50921. this._basePoint.subtractToRef(p2, this._tempVector);
  50922. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50923. c = this._tempVector.lengthSquared() - 1.0;
  50924. lowestRoot = getLowestRoot(a, b, c, t);
  50925. if (lowestRoot.found) {
  50926. t = lowestRoot.root;
  50927. found = true;
  50928. this._collisionPoint.copyFrom(p2);
  50929. }
  50930. this._basePoint.subtractToRef(p3, this._tempVector);
  50931. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50932. c = this._tempVector.lengthSquared() - 1.0;
  50933. lowestRoot = getLowestRoot(a, b, c, t);
  50934. if (lowestRoot.found) {
  50935. t = lowestRoot.root;
  50936. found = true;
  50937. this._collisionPoint.copyFrom(p3);
  50938. }
  50939. p2.subtractToRef(p1, this._edge);
  50940. p1.subtractToRef(this._basePoint, this._baseToVertex);
  50941. var edgeSquaredLength = this._edge.lengthSquared();
  50942. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50943. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50944. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50945. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50946. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50947. lowestRoot = getLowestRoot(a, b, c, t);
  50948. if (lowestRoot.found) {
  50949. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50950. if (f >= 0.0 && f <= 1.0) {
  50951. t = lowestRoot.root;
  50952. found = true;
  50953. this._edge.scaleInPlace(f);
  50954. p1.addToRef(this._edge, this._collisionPoint);
  50955. }
  50956. }
  50957. p3.subtractToRef(p2, this._edge);
  50958. p2.subtractToRef(this._basePoint, this._baseToVertex);
  50959. edgeSquaredLength = this._edge.lengthSquared();
  50960. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50961. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50962. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50963. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50964. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50965. lowestRoot = getLowestRoot(a, b, c, t);
  50966. if (lowestRoot.found) {
  50967. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50968. if (f >= 0.0 && f <= 1.0) {
  50969. t = lowestRoot.root;
  50970. found = true;
  50971. this._edge.scaleInPlace(f);
  50972. p2.addToRef(this._edge, this._collisionPoint);
  50973. }
  50974. }
  50975. p1.subtractToRef(p3, this._edge);
  50976. p3.subtractToRef(this._basePoint, this._baseToVertex);
  50977. edgeSquaredLength = this._edge.lengthSquared();
  50978. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50979. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50980. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50981. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50982. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50983. lowestRoot = getLowestRoot(a, b, c, t);
  50984. if (lowestRoot.found) {
  50985. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50986. if (f >= 0.0 && f <= 1.0) {
  50987. t = lowestRoot.root;
  50988. found = true;
  50989. this._edge.scaleInPlace(f);
  50990. p3.addToRef(this._edge, this._collisionPoint);
  50991. }
  50992. }
  50993. }
  50994. if (found) {
  50995. var distToCollision = t * this._velocity.length();
  50996. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  50997. if (!this.intersectionPoint) {
  50998. this.intersectionPoint = this._collisionPoint.clone();
  50999. }
  51000. else {
  51001. this.intersectionPoint.copyFrom(this._collisionPoint);
  51002. }
  51003. this._nearestDistance = distToCollision;
  51004. this.collisionFound = true;
  51005. }
  51006. }
  51007. };
  51008. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  51009. for (var i = indexStart; i < indexEnd; i += 3) {
  51010. var p1 = pts[indices[i] - decal];
  51011. var p2 = pts[indices[i + 1] - decal];
  51012. var p3 = pts[indices[i + 2] - decal];
  51013. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  51014. }
  51015. };
  51016. Collider.prototype._getResponse = function (pos, vel) {
  51017. pos.addToRef(vel, this._destinationPoint);
  51018. vel.scaleInPlace((this._nearestDistance / vel.length()));
  51019. this._basePoint.addToRef(vel, pos);
  51020. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  51021. this._slidePlaneNormal.normalize();
  51022. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  51023. pos.addInPlace(this._displacementVector);
  51024. this.intersectionPoint.addInPlace(this._displacementVector);
  51025. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  51026. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  51027. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  51028. };
  51029. return Collider;
  51030. }());
  51031. BABYLON.Collider = Collider;
  51032. })(BABYLON || (BABYLON = {}));
  51033. //# sourceMappingURL=babylon.collider.js.map
  51034. "use strict";
  51035. var BABYLON;
  51036. (function (BABYLON) {
  51037. //WebWorker code will be inserted to this variable.
  51038. BABYLON.CollisionWorker = "";
  51039. var WorkerTaskType;
  51040. (function (WorkerTaskType) {
  51041. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  51042. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  51043. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  51044. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  51045. var WorkerReplyType;
  51046. (function (WorkerReplyType) {
  51047. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  51048. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  51049. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  51050. var CollisionCoordinatorWorker = /** @class */ (function () {
  51051. function CollisionCoordinatorWorker() {
  51052. var _this = this;
  51053. this._scaledPosition = BABYLON.Vector3.Zero();
  51054. this._scaledVelocity = BABYLON.Vector3.Zero();
  51055. this.onMeshUpdated = function (transformNode) {
  51056. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  51057. };
  51058. this.onGeometryUpdated = function (geometry) {
  51059. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  51060. };
  51061. this._afterRender = function () {
  51062. if (!_this._init)
  51063. return;
  51064. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  51065. return;
  51066. }
  51067. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  51068. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  51069. if (_this._runningUpdated > 4) {
  51070. return;
  51071. }
  51072. ++_this._runningUpdated;
  51073. var payload = {
  51074. updatedMeshes: _this._addUpdateMeshesList,
  51075. updatedGeometries: _this._addUpdateGeometriesList,
  51076. removedGeometries: _this._toRemoveGeometryArray,
  51077. removedMeshes: _this._toRemoveMeshesArray
  51078. };
  51079. var message = {
  51080. payload: payload,
  51081. taskType: WorkerTaskType.UPDATE
  51082. };
  51083. var serializable = [];
  51084. for (var id in payload.updatedGeometries) {
  51085. if (payload.updatedGeometries.hasOwnProperty(id)) {
  51086. //prepare transferables
  51087. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  51088. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  51089. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  51090. }
  51091. }
  51092. _this._worker.postMessage(message, serializable);
  51093. _this._addUpdateMeshesList = {};
  51094. _this._addUpdateGeometriesList = {};
  51095. _this._toRemoveGeometryArray = [];
  51096. _this._toRemoveMeshesArray = [];
  51097. };
  51098. this._onMessageFromWorker = function (e) {
  51099. var returnData = e.data;
  51100. if (returnData.error != WorkerReplyType.SUCCESS) {
  51101. //TODO what errors can be returned from the worker?
  51102. BABYLON.Tools.Warn("error returned from worker!");
  51103. return;
  51104. }
  51105. switch (returnData.taskType) {
  51106. case WorkerTaskType.INIT:
  51107. _this._init = true;
  51108. //Update the worked with ALL of the scene's current state
  51109. _this._scene.meshes.forEach(function (mesh) {
  51110. _this.onMeshAdded(mesh);
  51111. });
  51112. _this._scene.getGeometries().forEach(function (geometry) {
  51113. _this.onGeometryAdded(geometry);
  51114. });
  51115. break;
  51116. case WorkerTaskType.UPDATE:
  51117. _this._runningUpdated--;
  51118. break;
  51119. case WorkerTaskType.COLLIDE:
  51120. var returnPayload = returnData.payload;
  51121. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  51122. return;
  51123. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  51124. if (callback) {
  51125. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  51126. if (mesh) {
  51127. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  51128. }
  51129. }
  51130. //cleanup
  51131. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  51132. break;
  51133. }
  51134. };
  51135. this._collisionsCallbackArray = [];
  51136. this._init = false;
  51137. this._runningUpdated = 0;
  51138. this._addUpdateMeshesList = {};
  51139. this._addUpdateGeometriesList = {};
  51140. this._toRemoveGeometryArray = [];
  51141. this._toRemoveMeshesArray = [];
  51142. }
  51143. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  51144. if (!this._init)
  51145. return;
  51146. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  51147. return;
  51148. position.divideToRef(collider._radius, this._scaledPosition);
  51149. displacement.divideToRef(collider._radius, this._scaledVelocity);
  51150. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  51151. var payload = {
  51152. collider: {
  51153. position: this._scaledPosition.asArray(),
  51154. velocity: this._scaledVelocity.asArray(),
  51155. radius: collider._radius.asArray()
  51156. },
  51157. collisionId: collisionIndex,
  51158. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  51159. maximumRetry: maximumRetry
  51160. };
  51161. var message = {
  51162. payload: payload,
  51163. taskType: WorkerTaskType.COLLIDE
  51164. };
  51165. this._worker.postMessage(message);
  51166. };
  51167. CollisionCoordinatorWorker.prototype.init = function (scene) {
  51168. this._scene = scene;
  51169. this._scene.registerAfterRender(this._afterRender);
  51170. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  51171. this._worker = new Worker(workerUrl);
  51172. this._worker.onmessage = this._onMessageFromWorker;
  51173. var message = {
  51174. payload: {},
  51175. taskType: WorkerTaskType.INIT
  51176. };
  51177. this._worker.postMessage(message);
  51178. };
  51179. CollisionCoordinatorWorker.prototype.destroy = function () {
  51180. this._scene.unregisterAfterRender(this._afterRender);
  51181. this._worker.terminate();
  51182. };
  51183. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  51184. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  51185. this.onMeshUpdated(mesh);
  51186. };
  51187. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  51188. this._toRemoveMeshesArray.push(mesh.uniqueId);
  51189. };
  51190. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  51191. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  51192. geometry.onGeometryUpdated = this.onGeometryUpdated;
  51193. this.onGeometryUpdated(geometry);
  51194. };
  51195. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  51196. this._toRemoveGeometryArray.push(geometry.id);
  51197. };
  51198. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  51199. var submeshes = [];
  51200. if (mesh.subMeshes) {
  51201. submeshes = mesh.subMeshes.map(function (sm, idx) {
  51202. var boundingInfo = sm.getBoundingInfo();
  51203. return {
  51204. position: idx,
  51205. verticesStart: sm.verticesStart,
  51206. verticesCount: sm.verticesCount,
  51207. indexStart: sm.indexStart,
  51208. indexCount: sm.indexCount,
  51209. hasMaterial: !!sm.getMaterial(),
  51210. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  51211. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  51212. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  51213. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  51214. };
  51215. });
  51216. }
  51217. var geometryId = null;
  51218. if (mesh instanceof BABYLON.Mesh) {
  51219. var geometry = mesh.geometry;
  51220. geometryId = geometry ? geometry.id : null;
  51221. }
  51222. else if (mesh instanceof BABYLON.InstancedMesh) {
  51223. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  51224. geometryId = geometry ? geometry.id : null;
  51225. }
  51226. var boundingInfo = mesh.getBoundingInfo();
  51227. return {
  51228. uniqueId: mesh.uniqueId,
  51229. id: mesh.id,
  51230. name: mesh.name,
  51231. geometryId: geometryId,
  51232. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  51233. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  51234. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  51235. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  51236. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  51237. subMeshes: submeshes,
  51238. checkCollisions: mesh.checkCollisions
  51239. };
  51240. };
  51241. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  51242. return {
  51243. id: geometry.id,
  51244. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  51245. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  51246. indices: new Uint32Array(geometry.getIndices() || []),
  51247. };
  51248. };
  51249. return CollisionCoordinatorWorker;
  51250. }());
  51251. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  51252. var CollisionCoordinatorLegacy = /** @class */ (function () {
  51253. function CollisionCoordinatorLegacy() {
  51254. this._scaledPosition = BABYLON.Vector3.Zero();
  51255. this._scaledVelocity = BABYLON.Vector3.Zero();
  51256. this._finalPosition = BABYLON.Vector3.Zero();
  51257. }
  51258. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  51259. position.divideToRef(collider._radius, this._scaledPosition);
  51260. displacement.divideToRef(collider._radius, this._scaledVelocity);
  51261. collider.collidedMesh = null;
  51262. collider._retry = 0;
  51263. collider._initialVelocity = this._scaledVelocity;
  51264. collider._initialPosition = this._scaledPosition;
  51265. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  51266. this._finalPosition.multiplyInPlace(collider._radius);
  51267. //run the callback
  51268. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  51269. };
  51270. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  51271. this._scene = scene;
  51272. };
  51273. CollisionCoordinatorLegacy.prototype.destroy = function () {
  51274. //Legacy need no destruction method.
  51275. };
  51276. //No update in legacy mode
  51277. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  51278. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  51279. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  51280. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  51281. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  51282. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  51283. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  51284. if (excludedMesh === void 0) { excludedMesh = null; }
  51285. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  51286. if (collider._retry >= maximumRetry) {
  51287. finalPosition.copyFrom(position);
  51288. return;
  51289. }
  51290. // Check if this is a mesh else camera or -1
  51291. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  51292. collider._initialize(position, velocity, closeDistance);
  51293. // Check all meshes
  51294. for (var index = 0; index < this._scene.meshes.length; index++) {
  51295. var mesh = this._scene.meshes[index];
  51296. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  51297. mesh._checkCollision(collider);
  51298. }
  51299. }
  51300. if (!collider.collisionFound) {
  51301. position.addToRef(velocity, finalPosition);
  51302. return;
  51303. }
  51304. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  51305. collider._getResponse(position, velocity);
  51306. }
  51307. if (velocity.length() <= closeDistance) {
  51308. finalPosition.copyFrom(position);
  51309. return;
  51310. }
  51311. collider._retry++;
  51312. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  51313. };
  51314. return CollisionCoordinatorLegacy;
  51315. }());
  51316. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  51317. })(BABYLON || (BABYLON = {}));
  51318. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  51319. "use strict";
  51320. var BABYLON;
  51321. (function (BABYLON) {
  51322. /**
  51323. * A particle represents one of the element emitted by a particle system.
  51324. * This is mainly define by its coordinates, direction, velocity and age.
  51325. */
  51326. var Particle = /** @class */ (function () {
  51327. /**
  51328. * Creates a new instance of @see Particle
  51329. * @param particleSystem the particle system the particle belongs to
  51330. */
  51331. function Particle(
  51332. /**
  51333. * particleSystem the particle system the particle belongs to.
  51334. */
  51335. particleSystem) {
  51336. this.particleSystem = particleSystem;
  51337. /**
  51338. * The world position of the particle in the scene.
  51339. */
  51340. this.position = BABYLON.Vector3.Zero();
  51341. /**
  51342. * The world direction of the particle in the scene.
  51343. */
  51344. this.direction = BABYLON.Vector3.Zero();
  51345. /**
  51346. * The color of the particle.
  51347. */
  51348. this.color = new BABYLON.Color4(0, 0, 0, 0);
  51349. /**
  51350. * The color change of the particle per step.
  51351. */
  51352. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  51353. /**
  51354. * Defines how long will the life of the particle be.
  51355. */
  51356. this.lifeTime = 1.0;
  51357. /**
  51358. * The current age of the particle.
  51359. */
  51360. this.age = 0;
  51361. /**
  51362. * The current size of the particle.
  51363. */
  51364. this.size = 0;
  51365. /**
  51366. * The current angle of the particle.
  51367. */
  51368. this.angle = 0;
  51369. /**
  51370. * Defines how fast is the angle changing.
  51371. */
  51372. this.angularSpeed = 0;
  51373. /**
  51374. * Defines the cell index used by the particle to be rendered from a sprite.
  51375. */
  51376. this.cellIndex = 0;
  51377. this._currentFrameCounter = 0;
  51378. if (!this.particleSystem.isAnimationSheetEnabled) {
  51379. return;
  51380. }
  51381. this.updateCellInfoFromSystem();
  51382. }
  51383. Particle.prototype.updateCellInfoFromSystem = function () {
  51384. this.cellIndex = this.particleSystem.startSpriteCellID;
  51385. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  51386. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  51387. }
  51388. else {
  51389. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  51390. }
  51391. };
  51392. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  51393. // (ageOffset / scaledUpdateSpeed) / available cells
  51394. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  51395. this._currentFrameCounter += scaledUpdateSpeed;
  51396. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  51397. this._currentFrameCounter = 0;
  51398. this.cellIndex++;
  51399. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51400. this.cellIndex = this.particleSystem.endSpriteCellID;
  51401. }
  51402. }
  51403. };
  51404. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  51405. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  51406. this.cellIndex++;
  51407. this._currentFrameCounter = 0;
  51408. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51409. if (this.particleSystem.spriteCellLoop) {
  51410. this.cellIndex = this.particleSystem.startSpriteCellID;
  51411. }
  51412. else {
  51413. this.cellIndex = this.particleSystem.endSpriteCellID;
  51414. }
  51415. }
  51416. }
  51417. else {
  51418. this._currentFrameCounter++;
  51419. }
  51420. };
  51421. /**
  51422. * Copy the properties of particle to another one.
  51423. * @param other the particle to copy the information to.
  51424. */
  51425. Particle.prototype.copyTo = function (other) {
  51426. other.position.copyFrom(this.position);
  51427. other.direction.copyFrom(this.direction);
  51428. other.color.copyFrom(this.color);
  51429. other.colorStep.copyFrom(this.colorStep);
  51430. other.lifeTime = this.lifeTime;
  51431. other.age = this.age;
  51432. other.size = this.size;
  51433. other.angle = this.angle;
  51434. other.angularSpeed = this.angularSpeed;
  51435. other.particleSystem = this.particleSystem;
  51436. other.cellIndex = this.cellIndex;
  51437. };
  51438. return Particle;
  51439. }());
  51440. BABYLON.Particle = Particle;
  51441. })(BABYLON || (BABYLON = {}));
  51442. //# sourceMappingURL=babylon.particle.js.map
  51443. "use strict";
  51444. var BABYLON;
  51445. (function (BABYLON) {
  51446. /**
  51447. * This represents a particle system in Babylon.
  51448. * 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.
  51449. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  51450. * @example https://doc.babylonjs.com/babylon101/particles
  51451. */
  51452. var ParticleSystem = /** @class */ (function () {
  51453. /**
  51454. * Instantiates a particle system.
  51455. * 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.
  51456. * @param name The name of the particle system
  51457. * @param capacity The max number of particles alive at the same time
  51458. * @param scene The scene the particle system belongs to
  51459. * @param customEffect a custom effect used to change the way particles are rendered by default
  51460. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  51461. * @param epsilon Offset used to render the particles
  51462. */
  51463. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  51464. if (customEffect === void 0) { customEffect = null; }
  51465. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  51466. if (epsilon === void 0) { epsilon = 0.01; }
  51467. var _this = this;
  51468. /**
  51469. * List of animations used by the particle system.
  51470. */
  51471. this.animations = [];
  51472. /**
  51473. * The rendering group used by the Particle system to chose when to render.
  51474. */
  51475. this.renderingGroupId = 0;
  51476. /**
  51477. * The emitter represents the Mesh or position we are attaching the particle system to.
  51478. */
  51479. this.emitter = null;
  51480. /**
  51481. * The maximum number of particles to emit per frame
  51482. */
  51483. this.emitRate = 10;
  51484. /**
  51485. * If you want to launch only a few particles at once, that can be done, as well.
  51486. */
  51487. this.manualEmitCount = -1;
  51488. /**
  51489. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  51490. */
  51491. this.updateSpeed = 0.01;
  51492. /**
  51493. * The amount of time the particle system is running (depends of the overall update speed).
  51494. */
  51495. this.targetStopDuration = 0;
  51496. /**
  51497. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  51498. */
  51499. this.disposeOnStop = false;
  51500. /**
  51501. * Minimum power of emitting particles.
  51502. */
  51503. this.minEmitPower = 1;
  51504. /**
  51505. * Maximum power of emitting particles.
  51506. */
  51507. this.maxEmitPower = 1;
  51508. /**
  51509. * Minimum life time of emitting particles.
  51510. */
  51511. this.minLifeTime = 1;
  51512. /**
  51513. * Maximum life time of emitting particles.
  51514. */
  51515. this.maxLifeTime = 1;
  51516. /**
  51517. * Minimum Size of emitting particles.
  51518. */
  51519. this.minSize = 1;
  51520. /**
  51521. * Maximum Size of emitting particles.
  51522. */
  51523. this.maxSize = 1;
  51524. /**
  51525. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  51526. */
  51527. this.minAngularSpeed = 0;
  51528. /**
  51529. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  51530. */
  51531. this.maxAngularSpeed = 0;
  51532. /**
  51533. * The layer mask we are rendering the particles through.
  51534. */
  51535. this.layerMask = 0x0FFFFFFF;
  51536. /**
  51537. * This can help using your own shader to render the particle system.
  51538. * The according effect will be created
  51539. */
  51540. this.customShader = null;
  51541. /**
  51542. * By default particle system starts as soon as they are created. This prevents the
  51543. * automatic start to happen and let you decide when to start emitting particles.
  51544. */
  51545. this.preventAutoStart = false;
  51546. /**
  51547. * Callback triggered when the particle animation is ending.
  51548. */
  51549. this.onAnimationEnd = null;
  51550. /**
  51551. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  51552. */
  51553. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  51554. /**
  51555. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  51556. * to override the particles.
  51557. */
  51558. this.forceDepthWrite = false;
  51559. /**
  51560. * You can use gravity if you want to give an orientation to your particles.
  51561. */
  51562. this.gravity = BABYLON.Vector3.Zero();
  51563. /**
  51564. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51565. */
  51566. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51567. /**
  51568. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51569. */
  51570. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51571. /**
  51572. * Color the particle will have at the end of its lifetime.
  51573. */
  51574. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  51575. /**
  51576. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  51577. */
  51578. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51579. /**
  51580. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  51581. */
  51582. this.spriteCellLoop = true;
  51583. /**
  51584. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  51585. */
  51586. this.spriteCellChangeSpeed = 0;
  51587. /**
  51588. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  51589. */
  51590. this.startSpriteCellID = 0;
  51591. /**
  51592. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  51593. */
  51594. this.endSpriteCellID = 0;
  51595. /**
  51596. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  51597. */
  51598. this.spriteCellWidth = 0;
  51599. /**
  51600. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  51601. */
  51602. this.spriteCellHeight = 0;
  51603. /**
  51604. * An event triggered when the system is disposed.
  51605. */
  51606. this.onDisposeObservable = new BABYLON.Observable();
  51607. this._particles = new Array();
  51608. this._stockParticles = new Array();
  51609. this._newPartsExcess = 0;
  51610. this._vertexBuffers = {};
  51611. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  51612. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  51613. this._scaledDirection = BABYLON.Vector3.Zero();
  51614. this._scaledGravity = BABYLON.Vector3.Zero();
  51615. this._currentRenderId = -1;
  51616. this._started = false;
  51617. this._stopped = false;
  51618. this._actualFrame = 0;
  51619. this._vertexBufferSize = 11;
  51620. // start of sub system methods
  51621. /**
  51622. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  51623. * Its lifetime will start back at 0.
  51624. */
  51625. this.recycleParticle = function (particle) {
  51626. var lastParticle = _this._particles.pop();
  51627. if (lastParticle !== particle) {
  51628. lastParticle.copyTo(particle);
  51629. }
  51630. _this._stockParticles.push(lastParticle);
  51631. };
  51632. this._createParticle = function () {
  51633. var particle;
  51634. if (_this._stockParticles.length !== 0) {
  51635. particle = _this._stockParticles.pop();
  51636. particle.age = 0;
  51637. particle.cellIndex = _this.startSpriteCellID;
  51638. }
  51639. else {
  51640. particle = new BABYLON.Particle(_this);
  51641. }
  51642. return particle;
  51643. };
  51644. this._emitFromParticle = function (particle) {
  51645. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  51646. return;
  51647. }
  51648. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  51649. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  51650. subSystem._rootParticleSystem = _this;
  51651. _this.activeSubSystems.push(subSystem);
  51652. subSystem.start();
  51653. };
  51654. this._appendParticleVertexes = null;
  51655. this.id = name;
  51656. this.name = name;
  51657. this._capacity = capacity;
  51658. this._epsilon = epsilon;
  51659. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  51660. if (isAnimationSheetEnabled) {
  51661. this._vertexBufferSize = 12;
  51662. }
  51663. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51664. this._customEffect = customEffect;
  51665. scene.particleSystems.push(this);
  51666. this._createIndexBuffer();
  51667. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  51668. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  51669. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  51670. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  51671. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  51672. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  51673. if (this._isAnimationSheetEnabled) {
  51674. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  51675. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  51676. }
  51677. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  51678. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  51679. this._vertexBuffers["options"] = options;
  51680. // Default emitter type
  51681. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  51682. this.updateFunction = function (particles) {
  51683. for (var index = 0; index < particles.length; index++) {
  51684. var particle = particles[index];
  51685. particle.age += _this._scaledUpdateSpeed;
  51686. if (particle.age >= particle.lifeTime) {
  51687. _this._emitFromParticle(particle);
  51688. _this.recycleParticle(particle);
  51689. index--;
  51690. continue;
  51691. }
  51692. else {
  51693. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  51694. particle.color.addInPlace(_this._scaledColorStep);
  51695. if (particle.color.a < 0)
  51696. particle.color.a = 0;
  51697. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  51698. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  51699. particle.position.addInPlace(_this._scaledDirection);
  51700. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  51701. particle.direction.addInPlace(_this._scaledGravity);
  51702. if (_this._isAnimationSheetEnabled) {
  51703. particle.updateCellIndex(_this._scaledUpdateSpeed);
  51704. }
  51705. }
  51706. }
  51707. };
  51708. }
  51709. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  51710. /**
  51711. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51712. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51713. */
  51714. get: function () {
  51715. if (this.particleEmitterType.direction1) {
  51716. return this.particleEmitterType.direction1;
  51717. }
  51718. return BABYLON.Vector3.Zero();
  51719. },
  51720. set: function (value) {
  51721. if (this.particleEmitterType.direction1) {
  51722. this.particleEmitterType.direction1 = value;
  51723. }
  51724. },
  51725. enumerable: true,
  51726. configurable: true
  51727. });
  51728. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  51729. /**
  51730. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51731. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51732. */
  51733. get: function () {
  51734. if (this.particleEmitterType.direction2) {
  51735. return this.particleEmitterType.direction2;
  51736. }
  51737. return BABYLON.Vector3.Zero();
  51738. },
  51739. set: function (value) {
  51740. if (this.particleEmitterType.direction2) {
  51741. this.particleEmitterType.direction2 = value;
  51742. }
  51743. },
  51744. enumerable: true,
  51745. configurable: true
  51746. });
  51747. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  51748. /**
  51749. * 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.
  51750. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51751. */
  51752. get: function () {
  51753. if (this.particleEmitterType.minEmitBox) {
  51754. return this.particleEmitterType.minEmitBox;
  51755. }
  51756. return BABYLON.Vector3.Zero();
  51757. },
  51758. set: function (value) {
  51759. if (this.particleEmitterType.minEmitBox) {
  51760. this.particleEmitterType.minEmitBox = value;
  51761. }
  51762. },
  51763. enumerable: true,
  51764. configurable: true
  51765. });
  51766. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  51767. /**
  51768. * 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.
  51769. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51770. */
  51771. get: function () {
  51772. if (this.particleEmitterType.maxEmitBox) {
  51773. return this.particleEmitterType.maxEmitBox;
  51774. }
  51775. return BABYLON.Vector3.Zero();
  51776. },
  51777. set: function (value) {
  51778. if (this.particleEmitterType.maxEmitBox) {
  51779. this.particleEmitterType.maxEmitBox = value;
  51780. }
  51781. },
  51782. enumerable: true,
  51783. configurable: true
  51784. });
  51785. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  51786. /**
  51787. * Sets a callback that will be triggered when the system is disposed.
  51788. */
  51789. set: function (callback) {
  51790. if (this._onDisposeObserver) {
  51791. this.onDisposeObservable.remove(this._onDisposeObserver);
  51792. }
  51793. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  51794. },
  51795. enumerable: true,
  51796. configurable: true
  51797. });
  51798. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  51799. /**
  51800. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  51801. */
  51802. get: function () {
  51803. return this._isAnimationSheetEnabled;
  51804. },
  51805. enumerable: true,
  51806. configurable: true
  51807. });
  51808. Object.defineProperty(ParticleSystem.prototype, "particles", {
  51809. //end of Sub-emitter
  51810. /**
  51811. * Gets the current list of active particles
  51812. */
  51813. get: function () {
  51814. return this._particles;
  51815. },
  51816. enumerable: true,
  51817. configurable: true
  51818. });
  51819. /**
  51820. * Returns the string "ParticleSystem"
  51821. * @returns a string containing the class name
  51822. */
  51823. ParticleSystem.prototype.getClassName = function () {
  51824. return "ParticleSystem";
  51825. };
  51826. ParticleSystem.prototype._createIndexBuffer = function () {
  51827. var indices = [];
  51828. var index = 0;
  51829. for (var count = 0; count < this._capacity; count++) {
  51830. indices.push(index);
  51831. indices.push(index + 1);
  51832. indices.push(index + 2);
  51833. indices.push(index);
  51834. indices.push(index + 2);
  51835. indices.push(index + 3);
  51836. index += 4;
  51837. }
  51838. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  51839. };
  51840. /**
  51841. * Gets the maximum number of particles active at the same time.
  51842. * @returns The max number of active particles.
  51843. */
  51844. ParticleSystem.prototype.getCapacity = function () {
  51845. return this._capacity;
  51846. };
  51847. /**
  51848. * Gets Wether there are still active particles in the system.
  51849. * @returns True if it is alive, otherwise false.
  51850. */
  51851. ParticleSystem.prototype.isAlive = function () {
  51852. return this._alive;
  51853. };
  51854. /**
  51855. * Gets Wether the system has been started.
  51856. * @returns True if it has been started, otherwise false.
  51857. */
  51858. ParticleSystem.prototype.isStarted = function () {
  51859. return this._started;
  51860. };
  51861. /**
  51862. * Starts the particle system and begins to emit.
  51863. */
  51864. ParticleSystem.prototype.start = function () {
  51865. this._started = true;
  51866. this._stopped = false;
  51867. this._actualFrame = 0;
  51868. if (this.subEmitters && this.subEmitters.length != 0) {
  51869. this.activeSubSystems = new Array();
  51870. }
  51871. };
  51872. /**
  51873. * Stops the particle system.
  51874. * @param stopSubEmitters if true it will stop the current system and all created sub-Systems if false it will stop the current root system only, this param is used by the root particle system only. the default value is true.
  51875. */
  51876. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  51877. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  51878. this._stopped = true;
  51879. if (stopSubEmitters) {
  51880. this._stopSubEmitters();
  51881. }
  51882. };
  51883. // animation sheet
  51884. /**
  51885. * Remove all active particles
  51886. */
  51887. ParticleSystem.prototype.reset = function () {
  51888. this._stockParticles = [];
  51889. this._particles = [];
  51890. };
  51891. /**
  51892. * @ignore (for internal use only)
  51893. */
  51894. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  51895. var offset = index * this._vertexBufferSize;
  51896. this._vertexData[offset] = particle.position.x;
  51897. this._vertexData[offset + 1] = particle.position.y;
  51898. this._vertexData[offset + 2] = particle.position.z;
  51899. this._vertexData[offset + 3] = particle.color.r;
  51900. this._vertexData[offset + 4] = particle.color.g;
  51901. this._vertexData[offset + 5] = particle.color.b;
  51902. this._vertexData[offset + 6] = particle.color.a;
  51903. this._vertexData[offset + 7] = particle.angle;
  51904. this._vertexData[offset + 8] = particle.size;
  51905. this._vertexData[offset + 9] = offsetX;
  51906. this._vertexData[offset + 10] = offsetY;
  51907. };
  51908. /**
  51909. * @ignore (for internal use only)
  51910. */
  51911. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  51912. if (offsetX === 0)
  51913. offsetX = this._epsilon;
  51914. else if (offsetX === 1)
  51915. offsetX = 1 - this._epsilon;
  51916. if (offsetY === 0)
  51917. offsetY = this._epsilon;
  51918. else if (offsetY === 1)
  51919. offsetY = 1 - this._epsilon;
  51920. var offset = index * this._vertexBufferSize;
  51921. this._vertexData[offset] = particle.position.x;
  51922. this._vertexData[offset + 1] = particle.position.y;
  51923. this._vertexData[offset + 2] = particle.position.z;
  51924. this._vertexData[offset + 3] = particle.color.r;
  51925. this._vertexData[offset + 4] = particle.color.g;
  51926. this._vertexData[offset + 5] = particle.color.b;
  51927. this._vertexData[offset + 6] = particle.color.a;
  51928. this._vertexData[offset + 7] = particle.angle;
  51929. this._vertexData[offset + 8] = particle.size;
  51930. this._vertexData[offset + 9] = offsetX;
  51931. this._vertexData[offset + 10] = offsetY;
  51932. this._vertexData[offset + 11] = particle.cellIndex;
  51933. };
  51934. ParticleSystem.prototype._stopSubEmitters = function () {
  51935. if (!this.activeSubSystems) {
  51936. return;
  51937. }
  51938. this.activeSubSystems.forEach(function (subSystem) {
  51939. subSystem.stop(true);
  51940. });
  51941. this.activeSubSystems = new Array();
  51942. };
  51943. ParticleSystem.prototype._removeFromRoot = function () {
  51944. if (!this._rootParticleSystem) {
  51945. return;
  51946. }
  51947. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  51948. if (index !== -1) {
  51949. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  51950. }
  51951. };
  51952. // end of sub system methods
  51953. ParticleSystem.prototype._update = function (newParticles) {
  51954. // Update current
  51955. this._alive = this._particles.length > 0;
  51956. this.updateFunction(this._particles);
  51957. // Add new ones
  51958. var worldMatrix;
  51959. if (this.emitter.position) {
  51960. var emitterMesh = this.emitter;
  51961. worldMatrix = emitterMesh.getWorldMatrix();
  51962. }
  51963. else {
  51964. var emitterPosition = this.emitter;
  51965. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  51966. }
  51967. var particle;
  51968. for (var index = 0; index < newParticles; index++) {
  51969. if (this._particles.length === this._capacity) {
  51970. break;
  51971. }
  51972. particle = this._createParticle();
  51973. this._particles.push(particle);
  51974. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  51975. if (this.startPositionFunction) {
  51976. this.startPositionFunction(worldMatrix, particle.position, particle);
  51977. }
  51978. else {
  51979. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  51980. }
  51981. if (this.startDirectionFunction) {
  51982. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51983. }
  51984. else {
  51985. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51986. }
  51987. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  51988. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  51989. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  51990. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  51991. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  51992. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  51993. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  51994. }
  51995. };
  51996. ParticleSystem.prototype._getEffect = function () {
  51997. if (this._customEffect) {
  51998. return this._customEffect;
  51999. }
  52000. ;
  52001. var defines = [];
  52002. if (this._scene.clipPlane) {
  52003. defines.push("#define CLIPPLANE");
  52004. }
  52005. if (this._isAnimationSheetEnabled) {
  52006. defines.push("#define ANIMATESHEET");
  52007. }
  52008. // Effect
  52009. var join = defines.join("\n");
  52010. if (this._cachedDefines !== join) {
  52011. this._cachedDefines = join;
  52012. var attributesNamesOrOptions;
  52013. var effectCreationOption;
  52014. if (this._isAnimationSheetEnabled) {
  52015. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  52016. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  52017. }
  52018. else {
  52019. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  52020. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  52021. }
  52022. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  52023. }
  52024. return this._effect;
  52025. };
  52026. /**
  52027. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  52028. */
  52029. ParticleSystem.prototype.animate = function () {
  52030. if (!this._started)
  52031. return;
  52032. var effect = this._getEffect();
  52033. // Check
  52034. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  52035. return;
  52036. if (this._currentRenderId === this._scene.getRenderId()) {
  52037. return;
  52038. }
  52039. this._currentRenderId = this._scene.getRenderId();
  52040. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  52041. // determine the number of particles we need to create
  52042. var newParticles;
  52043. if (this.manualEmitCount > -1) {
  52044. newParticles = this.manualEmitCount;
  52045. this._newPartsExcess = 0;
  52046. this.manualEmitCount = 0;
  52047. }
  52048. else {
  52049. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  52050. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  52051. }
  52052. if (this._newPartsExcess > 1.0) {
  52053. newParticles += this._newPartsExcess >> 0;
  52054. this._newPartsExcess -= this._newPartsExcess >> 0;
  52055. }
  52056. this._alive = false;
  52057. if (!this._stopped) {
  52058. this._actualFrame += this._scaledUpdateSpeed;
  52059. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  52060. this.stop();
  52061. }
  52062. else {
  52063. newParticles = 0;
  52064. }
  52065. this._update(newParticles);
  52066. // Stopped?
  52067. if (this._stopped) {
  52068. if (!this._alive) {
  52069. this._started = false;
  52070. if (this.onAnimationEnd) {
  52071. this.onAnimationEnd();
  52072. }
  52073. if (this.disposeOnStop) {
  52074. this._scene._toBeDisposed.push(this);
  52075. }
  52076. }
  52077. }
  52078. // Animation sheet
  52079. if (this._isAnimationSheetEnabled) {
  52080. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  52081. }
  52082. else {
  52083. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  52084. }
  52085. // Update VBO
  52086. var offset = 0;
  52087. for (var index = 0; index < this._particles.length; index++) {
  52088. var particle = this._particles[index];
  52089. this._appendParticleVertexes(offset, particle);
  52090. offset += 4;
  52091. }
  52092. if (this._vertexBuffer) {
  52093. this._vertexBuffer.update(this._vertexData);
  52094. }
  52095. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  52096. this.stop();
  52097. }
  52098. };
  52099. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  52100. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  52101. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  52102. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  52103. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  52104. };
  52105. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  52106. this._appendParticleVertex(offset++, particle, 0, 0);
  52107. this._appendParticleVertex(offset++, particle, 1, 0);
  52108. this._appendParticleVertex(offset++, particle, 1, 1);
  52109. this._appendParticleVertex(offset++, particle, 0, 1);
  52110. };
  52111. /**
  52112. * Rebuilds the particle system.
  52113. */
  52114. ParticleSystem.prototype.rebuild = function () {
  52115. this._createIndexBuffer();
  52116. if (this._vertexBuffer) {
  52117. this._vertexBuffer._rebuild();
  52118. }
  52119. };
  52120. /**
  52121. * Is this system ready to be used/rendered
  52122. * @return true if the system is ready
  52123. */
  52124. ParticleSystem.prototype.isReady = function () {
  52125. var effect = this._getEffect();
  52126. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  52127. return false;
  52128. }
  52129. return true;
  52130. };
  52131. /**
  52132. * Renders the particle system in its current state.
  52133. * @returns the current number of particles
  52134. */
  52135. ParticleSystem.prototype.render = function () {
  52136. var effect = this._getEffect();
  52137. // Check
  52138. if (!this.isReady() || !this._particles.length) {
  52139. return 0;
  52140. }
  52141. var engine = this._scene.getEngine();
  52142. // Render
  52143. engine.enableEffect(effect);
  52144. engine.setState(false);
  52145. var viewMatrix = this._scene.getViewMatrix();
  52146. effect.setTexture("diffuseSampler", this.particleTexture);
  52147. effect.setMatrix("view", viewMatrix);
  52148. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  52149. if (this._isAnimationSheetEnabled && this.particleTexture) {
  52150. var baseSize = this.particleTexture.getBaseSize();
  52151. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  52152. }
  52153. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  52154. if (this._scene.clipPlane) {
  52155. var clipPlane = this._scene.clipPlane;
  52156. var invView = viewMatrix.clone();
  52157. invView.invert();
  52158. effect.setMatrix("invView", invView);
  52159. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  52160. }
  52161. // VBOs
  52162. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  52163. // Draw order
  52164. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  52165. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  52166. }
  52167. else {
  52168. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52169. }
  52170. if (this.forceDepthWrite) {
  52171. engine.setDepthWrite(true);
  52172. }
  52173. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  52174. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52175. return this._particles.length;
  52176. };
  52177. /**
  52178. * Disposes the particle system and free the associated resources
  52179. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  52180. */
  52181. ParticleSystem.prototype.dispose = function (disposeTexture) {
  52182. if (disposeTexture === void 0) { disposeTexture = true; }
  52183. if (this._vertexBuffer) {
  52184. this._vertexBuffer.dispose();
  52185. this._vertexBuffer = null;
  52186. }
  52187. if (this._indexBuffer) {
  52188. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  52189. this._indexBuffer = null;
  52190. }
  52191. if (disposeTexture && this.particleTexture) {
  52192. this.particleTexture.dispose();
  52193. this.particleTexture = null;
  52194. }
  52195. this._removeFromRoot();
  52196. // Remove from scene
  52197. var index = this._scene.particleSystems.indexOf(this);
  52198. if (index > -1) {
  52199. this._scene.particleSystems.splice(index, 1);
  52200. }
  52201. // Callback
  52202. this.onDisposeObservable.notifyObservers(this);
  52203. this.onDisposeObservable.clear();
  52204. };
  52205. /**
  52206. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  52207. * @param radius The radius of the sphere to emit from
  52208. * @returns the emitter
  52209. */
  52210. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  52211. if (radius === void 0) { radius = 1; }
  52212. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  52213. this.particleEmitterType = particleEmitter;
  52214. return particleEmitter;
  52215. };
  52216. /**
  52217. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  52218. * @param radius The radius of the sphere to emit from
  52219. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  52220. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  52221. * @returns the emitter
  52222. */
  52223. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  52224. if (radius === void 0) { radius = 1; }
  52225. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  52226. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  52227. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  52228. this.particleEmitterType = particleEmitter;
  52229. return particleEmitter;
  52230. };
  52231. /**
  52232. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  52233. * @param radius The radius of the cone to emit from
  52234. * @param angle The base angle of the cone
  52235. * @returns the emitter
  52236. */
  52237. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  52238. if (radius === void 0) { radius = 1; }
  52239. if (angle === void 0) { angle = Math.PI / 4; }
  52240. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  52241. this.particleEmitterType = particleEmitter;
  52242. return particleEmitter;
  52243. };
  52244. // 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.
  52245. /**
  52246. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  52247. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  52248. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  52249. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52250. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52251. * @returns the emitter
  52252. */
  52253. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  52254. var particleEmitter = new BABYLON.BoxParticleEmitter();
  52255. this.particleEmitterType = particleEmitter;
  52256. this.direction1 = direction1;
  52257. this.direction2 = direction2;
  52258. this.minEmitBox = minEmitBox;
  52259. this.maxEmitBox = maxEmitBox;
  52260. return particleEmitter;
  52261. };
  52262. // Clone
  52263. /**
  52264. * Clones the particle system.
  52265. * @param name The name of the cloned object
  52266. * @param newEmitter The new emitter to use
  52267. * @returns the cloned particle system
  52268. */
  52269. ParticleSystem.prototype.clone = function (name, newEmitter) {
  52270. var custom = null;
  52271. var program = null;
  52272. if (this.customShader != null) {
  52273. program = this.customShader;
  52274. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52275. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52276. }
  52277. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  52278. result.customShader = program;
  52279. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  52280. if (newEmitter === undefined) {
  52281. newEmitter = this.emitter;
  52282. }
  52283. result.emitter = newEmitter;
  52284. if (this.particleTexture) {
  52285. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  52286. }
  52287. if (!this.preventAutoStart) {
  52288. result.start();
  52289. }
  52290. return result;
  52291. };
  52292. /**
  52293. * Serializes the particle system to a JSON object.
  52294. * @returns the JSON object
  52295. */
  52296. ParticleSystem.prototype.serialize = function () {
  52297. var serializationObject = {};
  52298. serializationObject.name = this.name;
  52299. serializationObject.id = this.id;
  52300. // Emitter
  52301. if (this.emitter.position) {
  52302. var emitterMesh = this.emitter;
  52303. serializationObject.emitterId = emitterMesh.id;
  52304. }
  52305. else {
  52306. var emitterPosition = this.emitter;
  52307. serializationObject.emitter = emitterPosition.asArray();
  52308. }
  52309. serializationObject.capacity = this.getCapacity();
  52310. if (this.particleTexture) {
  52311. serializationObject.textureName = this.particleTexture.name;
  52312. }
  52313. // Animations
  52314. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  52315. // Particle system
  52316. serializationObject.minAngularSpeed = this.minAngularSpeed;
  52317. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  52318. serializationObject.minSize = this.minSize;
  52319. serializationObject.maxSize = this.maxSize;
  52320. serializationObject.minEmitPower = this.minEmitPower;
  52321. serializationObject.maxEmitPower = this.maxEmitPower;
  52322. serializationObject.minLifeTime = this.minLifeTime;
  52323. serializationObject.maxLifeTime = this.maxLifeTime;
  52324. serializationObject.emitRate = this.emitRate;
  52325. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52326. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52327. serializationObject.gravity = this.gravity.asArray();
  52328. serializationObject.direction1 = this.direction1.asArray();
  52329. serializationObject.direction2 = this.direction2.asArray();
  52330. serializationObject.color1 = this.color1.asArray();
  52331. serializationObject.color2 = this.color2.asArray();
  52332. serializationObject.colorDead = this.colorDead.asArray();
  52333. serializationObject.updateSpeed = this.updateSpeed;
  52334. serializationObject.targetStopDuration = this.targetStopDuration;
  52335. serializationObject.textureMask = this.textureMask.asArray();
  52336. serializationObject.blendMode = this.blendMode;
  52337. serializationObject.customShader = this.customShader;
  52338. serializationObject.preventAutoStart = this.preventAutoStart;
  52339. serializationObject.startSpriteCellID = this.startSpriteCellID;
  52340. serializationObject.endSpriteCellID = this.endSpriteCellID;
  52341. serializationObject.spriteCellLoop = this.spriteCellLoop;
  52342. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  52343. serializationObject.spriteCellWidth = this.spriteCellWidth;
  52344. serializationObject.spriteCellHeight = this.spriteCellHeight;
  52345. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  52346. // Emitter
  52347. if (this.particleEmitterType) {
  52348. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  52349. }
  52350. return serializationObject;
  52351. };
  52352. /**
  52353. * Parses a JSON object to create a particle system.
  52354. * @param parsedParticleSystem The JSON object to parse
  52355. * @param scene The scene to create the particle system in
  52356. * @param rootUrl The root url to use to load external dependencies like texture
  52357. * @returns the Parsed particle system
  52358. */
  52359. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  52360. var name = parsedParticleSystem.name;
  52361. var custom = null;
  52362. var program = null;
  52363. if (parsedParticleSystem.customShader) {
  52364. program = parsedParticleSystem.customShader;
  52365. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52366. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52367. }
  52368. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  52369. particleSystem.customShader = program;
  52370. if (parsedParticleSystem.id) {
  52371. particleSystem.id = parsedParticleSystem.id;
  52372. }
  52373. // Auto start
  52374. if (parsedParticleSystem.preventAutoStart) {
  52375. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  52376. }
  52377. // Texture
  52378. if (parsedParticleSystem.textureName) {
  52379. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  52380. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  52381. }
  52382. // Emitter
  52383. if (parsedParticleSystem.emitterId) {
  52384. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  52385. }
  52386. else {
  52387. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  52388. }
  52389. // Animations
  52390. if (parsedParticleSystem.animations) {
  52391. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  52392. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  52393. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  52394. }
  52395. }
  52396. if (parsedParticleSystem.autoAnimate) {
  52397. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  52398. }
  52399. // Particle system
  52400. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  52401. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  52402. particleSystem.minSize = parsedParticleSystem.minSize;
  52403. particleSystem.maxSize = parsedParticleSystem.maxSize;
  52404. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  52405. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  52406. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  52407. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  52408. particleSystem.emitRate = parsedParticleSystem.emitRate;
  52409. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  52410. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  52411. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  52412. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  52413. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  52414. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  52415. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  52416. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  52417. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  52418. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  52419. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  52420. particleSystem.blendMode = parsedParticleSystem.blendMode;
  52421. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  52422. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  52423. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  52424. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  52425. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  52426. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  52427. if (!particleSystem.preventAutoStart) {
  52428. particleSystem.start();
  52429. }
  52430. return particleSystem;
  52431. };
  52432. /**
  52433. * Source color is added to the destination color without alpha affecting the result.
  52434. */
  52435. ParticleSystem.BLENDMODE_ONEONE = 0;
  52436. /**
  52437. * Blend current color and particle color using particle’s alpha.
  52438. */
  52439. ParticleSystem.BLENDMODE_STANDARD = 1;
  52440. return ParticleSystem;
  52441. }());
  52442. BABYLON.ParticleSystem = ParticleSystem;
  52443. })(BABYLON || (BABYLON = {}));
  52444. //# sourceMappingURL=babylon.particleSystem.js.map
  52445. "use strict";
  52446. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  52447. "use strict";
  52448. var BABYLON;
  52449. (function (BABYLON) {
  52450. /**
  52451. * Particle emitter emitting particles from the inside of a box.
  52452. * It emits the particles randomly between 2 given directions.
  52453. */
  52454. var BoxParticleEmitter = /** @class */ (function () {
  52455. /**
  52456. * Creates a new instance of @see BoxParticleEmitter
  52457. */
  52458. function BoxParticleEmitter() {
  52459. /**
  52460. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52461. */
  52462. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  52463. /**
  52464. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52465. */
  52466. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  52467. /**
  52468. * 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.
  52469. */
  52470. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  52471. /**
  52472. * 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.
  52473. */
  52474. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  52475. }
  52476. /**
  52477. * Called by the particle System when the direction is computed for the created particle.
  52478. * @param emitPower is the power of the particle (speed)
  52479. * @param worldMatrix is the world matrix of the particle system
  52480. * @param directionToUpdate is the direction vector to update with the result
  52481. * @param particle is the particle we are computed the direction for
  52482. */
  52483. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52484. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52485. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52486. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52487. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52488. };
  52489. /**
  52490. * Called by the particle System when the position is computed for the created particle.
  52491. * @param worldMatrix is the world matrix of the particle system
  52492. * @param positionToUpdate is the position vector to update with the result
  52493. * @param particle is the particle we are computed the position for
  52494. */
  52495. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52496. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  52497. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  52498. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  52499. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52500. };
  52501. /**
  52502. * Clones the current emitter and returns a copy of it
  52503. * @returns the new emitter
  52504. */
  52505. BoxParticleEmitter.prototype.clone = function () {
  52506. var newOne = new BoxParticleEmitter();
  52507. BABYLON.Tools.DeepCopy(this, newOne);
  52508. return newOne;
  52509. };
  52510. /**
  52511. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52512. * @param effect defines the update shader
  52513. */
  52514. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  52515. effect.setVector3("direction1", this.direction1);
  52516. effect.setVector3("direction2", this.direction2);
  52517. effect.setVector3("minEmitBox", this.minEmitBox);
  52518. effect.setVector3("maxEmitBox", this.maxEmitBox);
  52519. };
  52520. /**
  52521. * Returns a string to use to update the GPU particles update shader
  52522. * @returns a string containng the defines string
  52523. */
  52524. BoxParticleEmitter.prototype.getEffectDefines = function () {
  52525. return "#define BOXEMITTER";
  52526. };
  52527. /**
  52528. * Returns the string "BoxEmitter"
  52529. * @returns a string containing the class name
  52530. */
  52531. BoxParticleEmitter.prototype.getClassName = function () {
  52532. return "BoxEmitter";
  52533. };
  52534. /**
  52535. * Serializes the particle system to a JSON object.
  52536. * @returns the JSON object
  52537. */
  52538. BoxParticleEmitter.prototype.serialize = function () {
  52539. var serializationObject = {};
  52540. serializationObject.type = this.getClassName();
  52541. serializationObject.direction1 = this.direction1.asArray();
  52542. ;
  52543. serializationObject.direction2 = this.direction2.asArray();
  52544. ;
  52545. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52546. ;
  52547. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52548. ;
  52549. return serializationObject;
  52550. };
  52551. /**
  52552. * Parse properties from a JSON object
  52553. * @param serializationObject defines the JSON object
  52554. */
  52555. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  52556. this.direction1.copyFrom(serializationObject.direction1);
  52557. this.direction2.copyFrom(serializationObject.direction2);
  52558. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  52559. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  52560. };
  52561. return BoxParticleEmitter;
  52562. }());
  52563. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  52564. })(BABYLON || (BABYLON = {}));
  52565. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  52566. "use strict";
  52567. var BABYLON;
  52568. (function (BABYLON) {
  52569. /**
  52570. * Particle emitter emitting particles from the inside of a cone.
  52571. * It emits the particles alongside the cone volume from the base to the particle.
  52572. * The emission direction might be randomized.
  52573. */
  52574. var ConeParticleEmitter = /** @class */ (function () {
  52575. /**
  52576. * Creates a new instance of @see ConeParticleEmitter
  52577. * @param radius the radius of the emission cone (1 by default)
  52578. * @param angles the cone base angle (PI by default)
  52579. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52580. */
  52581. function ConeParticleEmitter(radius,
  52582. /**
  52583. * The radius of the emission cone.
  52584. */
  52585. angle,
  52586. /**
  52587. * The cone base angle.
  52588. */
  52589. directionRandomizer) {
  52590. if (radius === void 0) { radius = 1; }
  52591. if (angle === void 0) { angle = Math.PI; }
  52592. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52593. this.angle = angle;
  52594. this.directionRandomizer = directionRandomizer;
  52595. this.radius = radius;
  52596. }
  52597. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  52598. /**
  52599. * Gets the radius of the emission cone.
  52600. */
  52601. get: function () {
  52602. return this._radius;
  52603. },
  52604. /**
  52605. * Sets the radius of the emission cone.
  52606. */
  52607. set: function (value) {
  52608. this._radius = value;
  52609. if (this.angle !== 0) {
  52610. this._height = value / Math.tan(this.angle / 2);
  52611. }
  52612. else {
  52613. this._height = 1;
  52614. }
  52615. },
  52616. enumerable: true,
  52617. configurable: true
  52618. });
  52619. /**
  52620. * Called by the particle System when the direction is computed for the created particle.
  52621. * @param emitPower is the power of the particle (speed)
  52622. * @param worldMatrix is the world matrix of the particle system
  52623. * @param directionToUpdate is the direction vector to update with the result
  52624. * @param particle is the particle we are computed the direction for
  52625. */
  52626. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52627. if (this.angle === 0) {
  52628. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  52629. }
  52630. else {
  52631. // measure the direction Vector from the emitter to the particle.
  52632. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52633. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52634. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52635. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52636. direction.x += randX;
  52637. direction.y += randY;
  52638. direction.z += randZ;
  52639. direction.normalize();
  52640. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52641. }
  52642. };
  52643. /**
  52644. * Called by the particle System when the position is computed for the created particle.
  52645. * @param worldMatrix is the world matrix of the particle system
  52646. * @param positionToUpdate is the position vector to update with the result
  52647. * @param particle is the particle we are computed the position for
  52648. */
  52649. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52650. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  52651. var h = BABYLON.Scalar.RandomRange(0, 1);
  52652. // Better distribution in a cone at normal angles.
  52653. h = 1 - h * h;
  52654. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  52655. radius = radius * h;
  52656. var randX = radius * Math.sin(s);
  52657. var randZ = radius * Math.cos(s);
  52658. var randY = h * this._height;
  52659. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52660. };
  52661. /**
  52662. * Clones the current emitter and returns a copy of it
  52663. * @returns the new emitter
  52664. */
  52665. ConeParticleEmitter.prototype.clone = function () {
  52666. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  52667. BABYLON.Tools.DeepCopy(this, newOne);
  52668. return newOne;
  52669. };
  52670. /**
  52671. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52672. * @param effect defines the update shader
  52673. */
  52674. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  52675. effect.setFloat("radius", this.radius);
  52676. effect.setFloat("angle", this.angle);
  52677. effect.setFloat("height", this._height);
  52678. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52679. };
  52680. /**
  52681. * Returns a string to use to update the GPU particles update shader
  52682. * @returns a string containng the defines string
  52683. */
  52684. ConeParticleEmitter.prototype.getEffectDefines = function () {
  52685. return "#define CONEEMITTER";
  52686. };
  52687. /**
  52688. * Returns the string "BoxEmitter"
  52689. * @returns a string containing the class name
  52690. */
  52691. ConeParticleEmitter.prototype.getClassName = function () {
  52692. return "ConeEmitter";
  52693. };
  52694. /**
  52695. * Serializes the particle system to a JSON object.
  52696. * @returns the JSON object
  52697. */
  52698. ConeParticleEmitter.prototype.serialize = function () {
  52699. var serializationObject = {};
  52700. serializationObject.type = this.getClassName();
  52701. serializationObject.radius = this.radius;
  52702. serializationObject.angle = this.angle;
  52703. serializationObject.directionRandomizer = this.directionRandomizer;
  52704. return serializationObject;
  52705. };
  52706. /**
  52707. * Parse properties from a JSON object
  52708. * @param serializationObject defines the JSON object
  52709. */
  52710. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  52711. this.radius = serializationObject.radius;
  52712. this.angle = serializationObject.angle;
  52713. this.directionRandomizer = serializationObject.directionRandomizer;
  52714. };
  52715. return ConeParticleEmitter;
  52716. }());
  52717. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  52718. })(BABYLON || (BABYLON = {}));
  52719. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  52720. "use strict";
  52721. var BABYLON;
  52722. (function (BABYLON) {
  52723. /**
  52724. * Particle emitter emitting particles from the inside of a sphere.
  52725. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  52726. */
  52727. var SphereParticleEmitter = /** @class */ (function () {
  52728. /**
  52729. * Creates a new instance of @see SphereParticleEmitter
  52730. * @param radius the radius of the emission sphere (1 by default)
  52731. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52732. */
  52733. function SphereParticleEmitter(
  52734. /**
  52735. * The radius of the emission sphere.
  52736. */
  52737. radius,
  52738. /**
  52739. * How much to randomize the particle direction [0-1].
  52740. */
  52741. directionRandomizer) {
  52742. if (radius === void 0) { radius = 1; }
  52743. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52744. this.radius = radius;
  52745. this.directionRandomizer = directionRandomizer;
  52746. }
  52747. /**
  52748. * Called by the particle System when the direction is computed for the created particle.
  52749. * @param emitPower is the power of the particle (speed)
  52750. * @param worldMatrix is the world matrix of the particle system
  52751. * @param directionToUpdate is the direction vector to update with the result
  52752. * @param particle is the particle we are computed the direction for
  52753. */
  52754. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52755. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52756. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52757. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52758. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52759. direction.x += randX;
  52760. direction.y += randY;
  52761. direction.z += randZ;
  52762. direction.normalize();
  52763. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52764. };
  52765. /**
  52766. * Called by the particle System when the position is computed for the created particle.
  52767. * @param worldMatrix is the world matrix of the particle system
  52768. * @param positionToUpdate is the position vector to update with the result
  52769. * @param particle is the particle we are computed the position for
  52770. */
  52771. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52772. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  52773. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  52774. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  52775. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  52776. var randY = randRadius * Math.cos(theta);
  52777. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  52778. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52779. };
  52780. /**
  52781. * Clones the current emitter and returns a copy of it
  52782. * @returns the new emitter
  52783. */
  52784. SphereParticleEmitter.prototype.clone = function () {
  52785. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  52786. BABYLON.Tools.DeepCopy(this, newOne);
  52787. return newOne;
  52788. };
  52789. /**
  52790. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52791. * @param effect defines the update shader
  52792. */
  52793. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  52794. effect.setFloat("radius", this.radius);
  52795. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52796. };
  52797. /**
  52798. * Returns a string to use to update the GPU particles update shader
  52799. * @returns a string containng the defines string
  52800. */
  52801. SphereParticleEmitter.prototype.getEffectDefines = function () {
  52802. return "#define SPHEREEMITTER";
  52803. };
  52804. /**
  52805. * Returns the string "SphereParticleEmitter"
  52806. * @returns a string containing the class name
  52807. */
  52808. SphereParticleEmitter.prototype.getClassName = function () {
  52809. return "SphereParticleEmitter";
  52810. };
  52811. /**
  52812. * Serializes the particle system to a JSON object.
  52813. * @returns the JSON object
  52814. */
  52815. SphereParticleEmitter.prototype.serialize = function () {
  52816. var serializationObject = {};
  52817. serializationObject.type = this.getClassName();
  52818. serializationObject.radius = this.radius;
  52819. serializationObject.directionRandomizer = this.directionRandomizer;
  52820. return serializationObject;
  52821. };
  52822. /**
  52823. * Parse properties from a JSON object
  52824. * @param serializationObject defines the JSON object
  52825. */
  52826. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  52827. this.radius = serializationObject.radius;
  52828. this.directionRandomizer = serializationObject.directionRandomizer;
  52829. };
  52830. return SphereParticleEmitter;
  52831. }());
  52832. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  52833. /**
  52834. * Particle emitter emitting particles from the inside of a sphere.
  52835. * It emits the particles randomly between two vectors.
  52836. */
  52837. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  52838. __extends(SphereDirectedParticleEmitter, _super);
  52839. /**
  52840. * Creates a new instance of @see SphereDirectedParticleEmitter
  52841. * @param radius the radius of the emission sphere (1 by default)
  52842. * @param direction1 the min limit of the emission direction (up vector by default)
  52843. * @param direction2 the max limit of the emission direction (up vector by default)
  52844. */
  52845. function SphereDirectedParticleEmitter(radius,
  52846. /**
  52847. * The min limit of the emission direction.
  52848. */
  52849. direction1,
  52850. /**
  52851. * The max limit of the emission direction.
  52852. */
  52853. direction2) {
  52854. if (radius === void 0) { radius = 1; }
  52855. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  52856. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  52857. var _this = _super.call(this, radius) || this;
  52858. _this.direction1 = direction1;
  52859. _this.direction2 = direction2;
  52860. return _this;
  52861. }
  52862. /**
  52863. * Called by the particle System when the direction is computed for the created particle.
  52864. * @param emitPower is the power of the particle (speed)
  52865. * @param worldMatrix is the world matrix of the particle system
  52866. * @param directionToUpdate is the direction vector to update with the result
  52867. * @param particle is the particle we are computed the direction for
  52868. */
  52869. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52870. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52871. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52872. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52873. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52874. };
  52875. /**
  52876. * Clones the current emitter and returns a copy of it
  52877. * @returns the new emitter
  52878. */
  52879. SphereDirectedParticleEmitter.prototype.clone = function () {
  52880. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  52881. BABYLON.Tools.DeepCopy(this, newOne);
  52882. return newOne;
  52883. };
  52884. /**
  52885. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52886. * @param effect defines the update shader
  52887. */
  52888. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  52889. effect.setFloat("radius", this.radius);
  52890. effect.setVector3("direction1", this.direction1);
  52891. effect.setVector3("direction2", this.direction2);
  52892. };
  52893. /**
  52894. * Returns a string to use to update the GPU particles update shader
  52895. * @returns a string containng the defines string
  52896. */
  52897. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  52898. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  52899. };
  52900. /**
  52901. * Returns the string "SphereDirectedParticleEmitter"
  52902. * @returns a string containing the class name
  52903. */
  52904. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  52905. return "SphereDirectedParticleEmitter";
  52906. };
  52907. /**
  52908. * Serializes the particle system to a JSON object.
  52909. * @returns the JSON object
  52910. */
  52911. SphereDirectedParticleEmitter.prototype.serialize = function () {
  52912. var serializationObject = _super.prototype.serialize.call(this);
  52913. ;
  52914. serializationObject.direction1 = this.direction1.asArray();
  52915. ;
  52916. serializationObject.direction2 = this.direction2.asArray();
  52917. ;
  52918. return serializationObject;
  52919. };
  52920. /**
  52921. * Parse properties from a JSON object
  52922. * @param serializationObject defines the JSON object
  52923. */
  52924. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  52925. _super.prototype.parse.call(this, serializationObject);
  52926. this.direction1.copyFrom(serializationObject.direction1);
  52927. this.direction2.copyFrom(serializationObject.direction2);
  52928. };
  52929. return SphereDirectedParticleEmitter;
  52930. }(SphereParticleEmitter));
  52931. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  52932. })(BABYLON || (BABYLON = {}));
  52933. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  52934. "use strict";
  52935. var BABYLON;
  52936. (function (BABYLON) {
  52937. /**
  52938. * Represents one particle of a solid particle system.
  52939. * @see SolidParticleSystem
  52940. */
  52941. var SolidParticle = /** @class */ (function () {
  52942. /**
  52943. * Creates a Solid Particle object.
  52944. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  52945. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  52946. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  52947. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  52948. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  52949. * @param shapeId (integer) is the model shape identifier in the SPS.
  52950. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  52951. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  52952. */
  52953. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  52954. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  52955. /**
  52956. * particle global index
  52957. */
  52958. this.idx = 0;
  52959. /**
  52960. * The color of the particle
  52961. */
  52962. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52963. /**
  52964. * The world space position of the particle.
  52965. */
  52966. this.position = BABYLON.Vector3.Zero();
  52967. /**
  52968. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  52969. */
  52970. this.rotation = BABYLON.Vector3.Zero();
  52971. /**
  52972. * The scaling of the particle.
  52973. */
  52974. this.scaling = BABYLON.Vector3.One();
  52975. /**
  52976. * The uvs of the particle.
  52977. */
  52978. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  52979. /**
  52980. * The current speed of the particle.
  52981. */
  52982. this.velocity = BABYLON.Vector3.Zero();
  52983. /**
  52984. * The pivot point in the particle local space.
  52985. */
  52986. this.pivot = BABYLON.Vector3.Zero();
  52987. /**
  52988. * Must the particle be translated from its pivot point in its local space ?
  52989. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  52990. * Default : false
  52991. */
  52992. this.translateFromPivot = false;
  52993. /**
  52994. * Is the particle active or not ?
  52995. */
  52996. this.alive = true;
  52997. /**
  52998. * Is the particle visible or not ?
  52999. */
  53000. this.isVisible = true;
  53001. /**
  53002. * Index of this particle in the global "positions" array (Internal use)
  53003. */
  53004. this._pos = 0;
  53005. /**
  53006. * Index of this particle in the global "indices" array (Internal use)
  53007. */
  53008. this._ind = 0;
  53009. /**
  53010. * ModelShape id of this particle
  53011. */
  53012. this.shapeId = 0;
  53013. /**
  53014. * Index of the particle in its shape id (Internal use)
  53015. */
  53016. this.idxInShape = 0;
  53017. /**
  53018. * Still set as invisible in order to skip useless computations (Internal use)
  53019. */
  53020. this._stillInvisible = false;
  53021. /**
  53022. * Last computed particle rotation matrix
  53023. */
  53024. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  53025. /**
  53026. * Parent particle Id, if any.
  53027. * Default null.
  53028. */
  53029. this.parentId = null;
  53030. /**
  53031. * Internal global position in the SPS.
  53032. */
  53033. this._globalPosition = BABYLON.Vector3.Zero();
  53034. this.idx = particleIndex;
  53035. this._pos = positionIndex;
  53036. this._ind = indiceIndex;
  53037. this._model = model;
  53038. this.shapeId = shapeId;
  53039. this.idxInShape = idxInShape;
  53040. this._sps = sps;
  53041. if (modelBoundingInfo) {
  53042. this._modelBoundingInfo = modelBoundingInfo;
  53043. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  53044. }
  53045. }
  53046. Object.defineProperty(SolidParticle.prototype, "scale", {
  53047. /**
  53048. * Legacy support, changed scale to scaling
  53049. */
  53050. get: function () {
  53051. return this.scaling;
  53052. },
  53053. /**
  53054. * Legacy support, changed scale to scaling
  53055. */
  53056. set: function (scale) {
  53057. this.scaling = scale;
  53058. },
  53059. enumerable: true,
  53060. configurable: true
  53061. });
  53062. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  53063. /**
  53064. * Legacy support, changed quaternion to rotationQuaternion
  53065. */
  53066. get: function () {
  53067. return this.rotationQuaternion;
  53068. },
  53069. /**
  53070. * Legacy support, changed quaternion to rotationQuaternion
  53071. */
  53072. set: function (q) {
  53073. this.rotationQuaternion = q;
  53074. },
  53075. enumerable: true,
  53076. configurable: true
  53077. });
  53078. /**
  53079. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  53080. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  53081. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  53082. * @returns true if it intersects
  53083. */
  53084. SolidParticle.prototype.intersectsMesh = function (target) {
  53085. if (!this._boundingInfo || !target._boundingInfo) {
  53086. return false;
  53087. }
  53088. if (this._sps._bSphereOnly) {
  53089. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  53090. }
  53091. return this._boundingInfo.intersects(target._boundingInfo, false);
  53092. };
  53093. return SolidParticle;
  53094. }());
  53095. BABYLON.SolidParticle = SolidParticle;
  53096. /**
  53097. * Represents the shape of the model used by one particle of a solid particle system.
  53098. * SPS internal tool, don't use it manually.
  53099. * @see SolidParticleSystem
  53100. */
  53101. var ModelShape = /** @class */ (function () {
  53102. /**
  53103. * 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.
  53104. * SPS internal tool, don't use it manually.
  53105. * @ignore
  53106. */
  53107. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  53108. /**
  53109. * length of the shape in the model indices array (internal use)
  53110. */
  53111. this._indicesLength = 0;
  53112. this.shapeID = id;
  53113. this._shape = shape;
  53114. this._indicesLength = indicesLength;
  53115. this._shapeUV = shapeUV;
  53116. this._positionFunction = posFunction;
  53117. this._vertexFunction = vtxFunction;
  53118. }
  53119. return ModelShape;
  53120. }());
  53121. BABYLON.ModelShape = ModelShape;
  53122. /**
  53123. * Represents a Depth Sorted Particle in the solid particle system.
  53124. * @see SolidParticleSystem
  53125. */
  53126. var DepthSortedParticle = /** @class */ (function () {
  53127. function DepthSortedParticle() {
  53128. /**
  53129. * Index of the particle in the "indices" array
  53130. */
  53131. this.ind = 0;
  53132. /**
  53133. * Length of the particle shape in the "indices" array
  53134. */
  53135. this.indicesLength = 0;
  53136. /**
  53137. * Squared distance from the particle to the camera
  53138. */
  53139. this.sqDistance = 0.0;
  53140. }
  53141. return DepthSortedParticle;
  53142. }());
  53143. BABYLON.DepthSortedParticle = DepthSortedParticle;
  53144. })(BABYLON || (BABYLON = {}));
  53145. //# sourceMappingURL=babylon.solidParticle.js.map
  53146. "use strict";
  53147. var BABYLON;
  53148. (function (BABYLON) {
  53149. /**
  53150. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  53151. *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.
  53152. * The SPS is also a particle system. It provides some methods to manage the particles.
  53153. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  53154. *
  53155. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  53156. */
  53157. var SolidParticleSystem = /** @class */ (function () {
  53158. /**
  53159. * Creates a SPS (Solid Particle System) object.
  53160. * @param name (String) is the SPS name, this will be the underlying mesh name.
  53161. * @param scene (Scene) is the scene in which the SPS is added.
  53162. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  53163. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  53164. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  53165. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  53166. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  53167. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  53168. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  53169. */
  53170. function SolidParticleSystem(name, scene, options) {
  53171. /**
  53172. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  53173. * Example : var p = SPS.particles[i];
  53174. */
  53175. this.particles = new Array();
  53176. /**
  53177. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  53178. */
  53179. this.nbParticles = 0;
  53180. /**
  53181. * If the particles must ever face the camera (default false). Useful for planar particles.
  53182. */
  53183. this.billboard = false;
  53184. /**
  53185. * Recompute normals when adding a shape
  53186. */
  53187. this.recomputeNormals = true;
  53188. /**
  53189. * This a counter ofr your own usage. It's not set by any SPS functions.
  53190. */
  53191. this.counter = 0;
  53192. /**
  53193. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  53194. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  53195. */
  53196. this.vars = {};
  53197. /**
  53198. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  53199. */
  53200. this._bSphereOnly = false;
  53201. /**
  53202. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  53203. */
  53204. this._bSphereRadiusFactor = 1.0;
  53205. this._positions = new Array();
  53206. this._indices = new Array();
  53207. this._normals = new Array();
  53208. this._colors = new Array();
  53209. this._uvs = new Array();
  53210. this._index = 0; // indices index
  53211. this._updatable = true;
  53212. this._pickable = false;
  53213. this._isVisibilityBoxLocked = false;
  53214. this._alwaysVisible = false;
  53215. this._depthSort = false;
  53216. this._shapeCounter = 0;
  53217. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  53218. this._color = new BABYLON.Color4(0, 0, 0, 0);
  53219. this._computeParticleColor = true;
  53220. this._computeParticleTexture = true;
  53221. this._computeParticleRotation = true;
  53222. this._computeParticleVertex = false;
  53223. this._computeBoundingBox = false;
  53224. this._depthSortParticles = true;
  53225. this._cam_axisZ = BABYLON.Vector3.Zero();
  53226. this._cam_axisY = BABYLON.Vector3.Zero();
  53227. this._cam_axisX = BABYLON.Vector3.Zero();
  53228. this._axisZ = BABYLON.Axis.Z;
  53229. this._camDir = BABYLON.Vector3.Zero();
  53230. this._camInvertedPosition = BABYLON.Vector3.Zero();
  53231. this._rotMatrix = new BABYLON.Matrix();
  53232. this._invertMatrix = new BABYLON.Matrix();
  53233. this._rotated = BABYLON.Vector3.Zero();
  53234. this._quaternion = new BABYLON.Quaternion();
  53235. this._vertex = BABYLON.Vector3.Zero();
  53236. this._normal = BABYLON.Vector3.Zero();
  53237. this._yaw = 0.0;
  53238. this._pitch = 0.0;
  53239. this._roll = 0.0;
  53240. this._halfroll = 0.0;
  53241. this._halfpitch = 0.0;
  53242. this._halfyaw = 0.0;
  53243. this._sinRoll = 0.0;
  53244. this._cosRoll = 0.0;
  53245. this._sinPitch = 0.0;
  53246. this._cosPitch = 0.0;
  53247. this._sinYaw = 0.0;
  53248. this._cosYaw = 0.0;
  53249. this._mustUnrotateFixedNormals = false;
  53250. this._minimum = BABYLON.Vector3.Zero();
  53251. this._maximum = BABYLON.Vector3.Zero();
  53252. this._minBbox = BABYLON.Vector3.Zero();
  53253. this._maxBbox = BABYLON.Vector3.Zero();
  53254. this._particlesIntersect = false;
  53255. this._depthSortFunction = function (p1, p2) {
  53256. return (p2.sqDistance - p1.sqDistance);
  53257. };
  53258. this._needs32Bits = false;
  53259. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  53260. this._scaledPivot = BABYLON.Vector3.Zero();
  53261. this._particleHasParent = false;
  53262. this.name = name;
  53263. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53264. this._camera = scene.activeCamera;
  53265. this._pickable = options ? options.isPickable : false;
  53266. this._depthSort = options ? options.enableDepthSort : false;
  53267. this._particlesIntersect = options ? options.particleIntersection : false;
  53268. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  53269. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  53270. if (options && options.updatable) {
  53271. this._updatable = options.updatable;
  53272. }
  53273. else {
  53274. this._updatable = true;
  53275. }
  53276. if (this._pickable) {
  53277. this.pickedParticles = [];
  53278. }
  53279. if (this._depthSort) {
  53280. this.depthSortedParticles = [];
  53281. }
  53282. }
  53283. /**
  53284. * Builds the SPS underlying mesh. Returns a standard Mesh.
  53285. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  53286. * @returns the created mesh
  53287. */
  53288. SolidParticleSystem.prototype.buildMesh = function () {
  53289. if (this.nbParticles === 0) {
  53290. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  53291. this.addShape(triangle, 1);
  53292. triangle.dispose();
  53293. }
  53294. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  53295. this._positions32 = new Float32Array(this._positions);
  53296. this._uvs32 = new Float32Array(this._uvs);
  53297. this._colors32 = new Float32Array(this._colors);
  53298. if (this.recomputeNormals) {
  53299. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  53300. }
  53301. this._normals32 = new Float32Array(this._normals);
  53302. this._fixedNormal32 = new Float32Array(this._normals);
  53303. if (this._mustUnrotateFixedNormals) {
  53304. this._unrotateFixedNormals();
  53305. }
  53306. var vertexData = new BABYLON.VertexData();
  53307. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  53308. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  53309. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  53310. if (this._uvs32) {
  53311. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  53312. ;
  53313. }
  53314. if (this._colors32) {
  53315. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  53316. }
  53317. var mesh = new BABYLON.Mesh(this.name, this._scene);
  53318. vertexData.applyToMesh(mesh, this._updatable);
  53319. this.mesh = mesh;
  53320. this.mesh.isPickable = this._pickable;
  53321. // free memory
  53322. if (!this._depthSort) {
  53323. this._indices = null;
  53324. }
  53325. this._positions = null;
  53326. this._normals = null;
  53327. this._uvs = null;
  53328. this._colors = null;
  53329. if (!this._updatable) {
  53330. this.particles.length = 0;
  53331. }
  53332. return mesh;
  53333. };
  53334. /**
  53335. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  53336. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  53337. * Thus the particles generated from `digest()` have their property `position` set yet.
  53338. * @param mesh ( Mesh ) is the mesh to be digested
  53339. * @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
  53340. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  53341. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  53342. * @returns the current SPS
  53343. */
  53344. SolidParticleSystem.prototype.digest = function (mesh, options) {
  53345. var size = (options && options.facetNb) || 1;
  53346. var number = (options && options.number) || 0;
  53347. var delta = (options && options.delta) || 0;
  53348. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53349. var meshInd = mesh.getIndices();
  53350. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53351. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53352. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53353. var f = 0; // facet counter
  53354. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  53355. // compute size from number
  53356. if (number) {
  53357. number = (number > totalFacets) ? totalFacets : number;
  53358. size = Math.round(totalFacets / number);
  53359. delta = 0;
  53360. }
  53361. else {
  53362. size = (size > totalFacets) ? totalFacets : size;
  53363. }
  53364. var facetPos = []; // submesh positions
  53365. var facetInd = []; // submesh indices
  53366. var facetUV = []; // submesh UV
  53367. var facetCol = []; // submesh colors
  53368. var barycenter = BABYLON.Vector3.Zero();
  53369. var sizeO = size;
  53370. while (f < totalFacets) {
  53371. size = sizeO + Math.floor((1 + delta) * Math.random());
  53372. if (f > totalFacets - size) {
  53373. size = totalFacets - f;
  53374. }
  53375. // reset temp arrays
  53376. facetPos.length = 0;
  53377. facetInd.length = 0;
  53378. facetUV.length = 0;
  53379. facetCol.length = 0;
  53380. // iterate over "size" facets
  53381. var fi = 0;
  53382. for (var j = f * 3; j < (f + size) * 3; j++) {
  53383. facetInd.push(fi);
  53384. var i = meshInd[j];
  53385. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  53386. if (meshUV) {
  53387. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  53388. }
  53389. if (meshCol) {
  53390. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  53391. }
  53392. fi++;
  53393. }
  53394. // create a model shape for each single particle
  53395. var idx = this.nbParticles;
  53396. var shape = this._posToShape(facetPos);
  53397. var shapeUV = this._uvsToShapeUV(facetUV);
  53398. // compute the barycenter of the shape
  53399. var v;
  53400. for (v = 0; v < shape.length; v++) {
  53401. barycenter.addInPlace(shape[v]);
  53402. }
  53403. barycenter.scaleInPlace(1 / shape.length);
  53404. // shift the shape from its barycenter to the origin
  53405. for (v = 0; v < shape.length; v++) {
  53406. shape[v].subtractInPlace(barycenter);
  53407. }
  53408. var bInfo;
  53409. if (this._particlesIntersect) {
  53410. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  53411. }
  53412. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  53413. // add the particle in the SPS
  53414. var currentPos = this._positions.length;
  53415. var currentInd = this._indices.length;
  53416. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  53417. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  53418. // initialize the particle position
  53419. this.particles[this.nbParticles].position.addInPlace(barycenter);
  53420. this._index += shape.length;
  53421. idx++;
  53422. this.nbParticles++;
  53423. this._shapeCounter++;
  53424. f += size;
  53425. }
  53426. return this;
  53427. };
  53428. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  53429. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  53430. var index = 0;
  53431. var idx = 0;
  53432. for (var p = 0; p < this.particles.length; p++) {
  53433. this._particle = this.particles[p];
  53434. this._shape = this._particle._model._shape;
  53435. if (this._particle.rotationQuaternion) {
  53436. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53437. }
  53438. else {
  53439. this._yaw = this._particle.rotation.y;
  53440. this._pitch = this._particle.rotation.x;
  53441. this._roll = this._particle.rotation.z;
  53442. this._quaternionRotationYPR();
  53443. }
  53444. this._quaternionToRotationMatrix();
  53445. this._rotMatrix.invertToRef(this._invertMatrix);
  53446. for (var pt = 0; pt < this._shape.length; pt++) {
  53447. idx = index + pt * 3;
  53448. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  53449. this._fixedNormal32[idx] = this._normal.x;
  53450. this._fixedNormal32[idx + 1] = this._normal.y;
  53451. this._fixedNormal32[idx + 2] = this._normal.z;
  53452. }
  53453. index = idx + 3;
  53454. }
  53455. };
  53456. //reset copy
  53457. SolidParticleSystem.prototype._resetCopy = function () {
  53458. this._copy.position.x = 0;
  53459. this._copy.position.y = 0;
  53460. this._copy.position.z = 0;
  53461. this._copy.rotation.x = 0;
  53462. this._copy.rotation.y = 0;
  53463. this._copy.rotation.z = 0;
  53464. this._copy.rotationQuaternion = null;
  53465. this._copy.scaling.x = 1.0;
  53466. this._copy.scaling.y = 1.0;
  53467. this._copy.scaling.z = 1.0;
  53468. this._copy.uvs.x = 0;
  53469. this._copy.uvs.y = 0;
  53470. this._copy.uvs.z = 1.0;
  53471. this._copy.uvs.w = 1.0;
  53472. this._copy.color = null;
  53473. this._copy.translateFromPivot = false;
  53474. };
  53475. // _meshBuilder : inserts the shape model in the global SPS mesh
  53476. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  53477. var i;
  53478. var u = 0;
  53479. var c = 0;
  53480. var n = 0;
  53481. this._resetCopy();
  53482. if (options && options.positionFunction) {
  53483. options.positionFunction(this._copy, idx, idxInShape);
  53484. this._mustUnrotateFixedNormals = true;
  53485. }
  53486. if (this._copy.rotationQuaternion) {
  53487. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  53488. }
  53489. else {
  53490. this._yaw = this._copy.rotation.y;
  53491. this._pitch = this._copy.rotation.x;
  53492. this._roll = this._copy.rotation.z;
  53493. this._quaternionRotationYPR();
  53494. }
  53495. this._quaternionToRotationMatrix();
  53496. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  53497. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  53498. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  53499. if (this._copy.translateFromPivot) {
  53500. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  53501. }
  53502. else {
  53503. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  53504. }
  53505. for (i = 0; i < shape.length; i++) {
  53506. this._vertex.x = shape[i].x;
  53507. this._vertex.y = shape[i].y;
  53508. this._vertex.z = shape[i].z;
  53509. if (options && options.vertexFunction) {
  53510. options.vertexFunction(this._copy, this._vertex, i);
  53511. }
  53512. this._vertex.x *= this._copy.scaling.x;
  53513. this._vertex.y *= this._copy.scaling.y;
  53514. this._vertex.z *= this._copy.scaling.z;
  53515. this._vertex.x -= this._scaledPivot.x;
  53516. this._vertex.y -= this._scaledPivot.y;
  53517. this._vertex.z -= this._scaledPivot.z;
  53518. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53519. this._rotated.addInPlace(this._pivotBackTranslation);
  53520. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  53521. if (meshUV) {
  53522. 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);
  53523. u += 2;
  53524. }
  53525. if (this._copy.color) {
  53526. this._color = this._copy.color;
  53527. }
  53528. else if (meshCol && meshCol[c] !== undefined) {
  53529. this._color.r = meshCol[c];
  53530. this._color.g = meshCol[c + 1];
  53531. this._color.b = meshCol[c + 2];
  53532. this._color.a = meshCol[c + 3];
  53533. }
  53534. else {
  53535. this._color.r = 1.0;
  53536. this._color.g = 1.0;
  53537. this._color.b = 1.0;
  53538. this._color.a = 1.0;
  53539. }
  53540. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  53541. c += 4;
  53542. if (!this.recomputeNormals && meshNor) {
  53543. this._normal.x = meshNor[n];
  53544. this._normal.y = meshNor[n + 1];
  53545. this._normal.z = meshNor[n + 2];
  53546. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  53547. normals.push(this._normal.x, this._normal.y, this._normal.z);
  53548. n += 3;
  53549. }
  53550. }
  53551. for (i = 0; i < meshInd.length; i++) {
  53552. var current_ind = p + meshInd[i];
  53553. indices.push(current_ind);
  53554. if (current_ind > 65535) {
  53555. this._needs32Bits = true;
  53556. }
  53557. }
  53558. if (this._pickable) {
  53559. var nbfaces = meshInd.length / 3;
  53560. for (i = 0; i < nbfaces; i++) {
  53561. this.pickedParticles.push({ idx: idx, faceId: i });
  53562. }
  53563. }
  53564. if (this._depthSort) {
  53565. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  53566. }
  53567. return this._copy;
  53568. };
  53569. // returns a shape array from positions array
  53570. SolidParticleSystem.prototype._posToShape = function (positions) {
  53571. var shape = [];
  53572. for (var i = 0; i < positions.length; i += 3) {
  53573. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  53574. }
  53575. return shape;
  53576. };
  53577. // returns a shapeUV array from a Vector4 uvs
  53578. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  53579. var shapeUV = [];
  53580. if (uvs) {
  53581. for (var i = 0; i < uvs.length; i++)
  53582. shapeUV.push(uvs[i]);
  53583. }
  53584. return shapeUV;
  53585. };
  53586. // adds a new particle object in the particles array
  53587. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  53588. if (bInfo === void 0) { bInfo = null; }
  53589. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  53590. this.particles.push(sp);
  53591. return sp;
  53592. };
  53593. /**
  53594. * Adds some particles to the SPS from the model shape. Returns the shape id.
  53595. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  53596. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  53597. * @param nb (positive integer) the number of particles to be created from this model
  53598. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  53599. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  53600. * @returns the number of shapes in the system
  53601. */
  53602. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  53603. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53604. var meshInd = mesh.getIndices();
  53605. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53606. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53607. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53608. var bbInfo;
  53609. if (this._particlesIntersect) {
  53610. bbInfo = mesh.getBoundingInfo();
  53611. }
  53612. var shape = this._posToShape(meshPos);
  53613. var shapeUV = this._uvsToShapeUV(meshUV);
  53614. var posfunc = options ? options.positionFunction : null;
  53615. var vtxfunc = options ? options.vertexFunction : null;
  53616. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  53617. // particles
  53618. var sp;
  53619. var currentCopy;
  53620. var idx = this.nbParticles;
  53621. for (var i = 0; i < nb; i++) {
  53622. var currentPos = this._positions.length;
  53623. var currentInd = this._indices.length;
  53624. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  53625. if (this._updatable) {
  53626. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  53627. sp.position.copyFrom(currentCopy.position);
  53628. sp.rotation.copyFrom(currentCopy.rotation);
  53629. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  53630. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  53631. }
  53632. if (currentCopy.color && sp.color) {
  53633. sp.color.copyFrom(currentCopy.color);
  53634. }
  53635. sp.scaling.copyFrom(currentCopy.scaling);
  53636. sp.uvs.copyFrom(currentCopy.uvs);
  53637. }
  53638. this._index += shape.length;
  53639. idx++;
  53640. }
  53641. this.nbParticles += nb;
  53642. this._shapeCounter++;
  53643. return this._shapeCounter - 1;
  53644. };
  53645. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  53646. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  53647. this._resetCopy();
  53648. if (particle._model._positionFunction) {
  53649. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  53650. }
  53651. if (this._copy.rotationQuaternion) {
  53652. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  53653. }
  53654. else {
  53655. this._yaw = this._copy.rotation.y;
  53656. this._pitch = this._copy.rotation.x;
  53657. this._roll = this._copy.rotation.z;
  53658. this._quaternionRotationYPR();
  53659. }
  53660. this._quaternionToRotationMatrix();
  53661. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  53662. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  53663. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  53664. if (this._copy.translateFromPivot) {
  53665. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  53666. }
  53667. else {
  53668. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  53669. }
  53670. this._shape = particle._model._shape;
  53671. for (var pt = 0; pt < this._shape.length; pt++) {
  53672. this._vertex.x = this._shape[pt].x;
  53673. this._vertex.y = this._shape[pt].y;
  53674. this._vertex.z = this._shape[pt].z;
  53675. if (particle._model._vertexFunction) {
  53676. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  53677. }
  53678. this._vertex.x *= this._copy.scaling.x;
  53679. this._vertex.y *= this._copy.scaling.y;
  53680. this._vertex.z *= this._copy.scaling.z;
  53681. this._vertex.x -= this._scaledPivot.x;
  53682. this._vertex.y -= this._scaledPivot.y;
  53683. this._vertex.z -= this._scaledPivot.z;
  53684. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53685. this._rotated.addInPlace(this._pivotBackTranslation);
  53686. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  53687. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  53688. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  53689. }
  53690. particle.position.x = 0.0;
  53691. particle.position.y = 0.0;
  53692. particle.position.z = 0.0;
  53693. particle.rotation.x = 0.0;
  53694. particle.rotation.y = 0.0;
  53695. particle.rotation.z = 0.0;
  53696. particle.rotationQuaternion = null;
  53697. particle.scaling.x = 1.0;
  53698. particle.scaling.y = 1.0;
  53699. particle.scaling.z = 1.0;
  53700. particle.uvs.x = 0.0;
  53701. particle.uvs.y = 0.0;
  53702. particle.uvs.z = 1.0;
  53703. particle.uvs.w = 1.0;
  53704. particle.pivot.x = 0.0;
  53705. particle.pivot.y = 0.0;
  53706. particle.pivot.z = 0.0;
  53707. particle.translateFromPivot = false;
  53708. particle.parentId = null;
  53709. };
  53710. /**
  53711. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  53712. * @returns the SPS.
  53713. */
  53714. SolidParticleSystem.prototype.rebuildMesh = function () {
  53715. for (var p = 0; p < this.particles.length; p++) {
  53716. this._rebuildParticle(this.particles[p]);
  53717. }
  53718. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53719. return this;
  53720. };
  53721. /**
  53722. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  53723. * This method calls `updateParticle()` for each particle of the SPS.
  53724. * For an animated SPS, it is usually called within the render loop.
  53725. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  53726. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  53727. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  53728. * @returns the SPS.
  53729. */
  53730. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  53731. if (start === void 0) { start = 0; }
  53732. if (end === void 0) { end = this.nbParticles - 1; }
  53733. if (update === void 0) { update = true; }
  53734. if (!this._updatable) {
  53735. return this;
  53736. }
  53737. // custom beforeUpdate
  53738. this.beforeUpdateParticles(start, end, update);
  53739. this._cam_axisX.x = 1.0;
  53740. this._cam_axisX.y = 0.0;
  53741. this._cam_axisX.z = 0.0;
  53742. this._cam_axisY.x = 0.0;
  53743. this._cam_axisY.y = 1.0;
  53744. this._cam_axisY.z = 0.0;
  53745. this._cam_axisZ.x = 0.0;
  53746. this._cam_axisZ.y = 0.0;
  53747. this._cam_axisZ.z = 1.0;
  53748. // cases when the World Matrix is to be computed first
  53749. if (this.billboard || this._depthSort) {
  53750. this.mesh.computeWorldMatrix(true);
  53751. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  53752. }
  53753. // if the particles will always face the camera
  53754. if (this.billboard) {
  53755. // compute the camera position and un-rotate it by the current mesh rotation
  53756. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  53757. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  53758. this._cam_axisZ.normalize();
  53759. // same for camera up vector extracted from the cam view matrix
  53760. var view = this._camera.getViewMatrix(true);
  53761. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  53762. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  53763. this._cam_axisY.normalize();
  53764. this._cam_axisX.normalize();
  53765. }
  53766. // if depthSort, compute the camera global position in the mesh local system
  53767. if (this._depthSort) {
  53768. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  53769. }
  53770. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  53771. var idx = 0; // current position index in the global array positions32
  53772. var index = 0; // position start index in the global array positions32 of the current particle
  53773. var colidx = 0; // current color index in the global array colors32
  53774. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  53775. var uvidx = 0; // current uv index in the global array uvs32
  53776. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  53777. var pt = 0; // current index in the particle model shape
  53778. if (this.mesh.isFacetDataEnabled) {
  53779. this._computeBoundingBox = true;
  53780. }
  53781. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  53782. if (this._computeBoundingBox) {
  53783. if (start == 0 && end == this.nbParticles - 1) {
  53784. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  53785. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  53786. }
  53787. else {
  53788. if (this.mesh._boundingInfo) {
  53789. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  53790. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  53791. }
  53792. }
  53793. }
  53794. // particle loop
  53795. index = this.particles[start]._pos;
  53796. var vpos = (index / 3) | 0;
  53797. colorIndex = vpos * 4;
  53798. uvIndex = vpos * 2;
  53799. for (var p = start; p <= end; p++) {
  53800. this._particle = this.particles[p];
  53801. this._shape = this._particle._model._shape;
  53802. this._shapeUV = this._particle._model._shapeUV;
  53803. // call to custom user function to update the particle properties
  53804. this.updateParticle(this._particle);
  53805. // camera-particle distance for depth sorting
  53806. if (this._depthSort && this._depthSortParticles) {
  53807. var dsp = this.depthSortedParticles[p];
  53808. dsp.ind = this._particle._ind;
  53809. dsp.indicesLength = this._particle._model._indicesLength;
  53810. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  53811. }
  53812. // skip the computations for inactive or already invisible particles
  53813. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  53814. // increment indexes for the next particle
  53815. pt = this._shape.length;
  53816. index += pt * 3;
  53817. colorIndex += pt * 4;
  53818. uvIndex += pt * 2;
  53819. continue;
  53820. }
  53821. if (this._particle.isVisible) {
  53822. this._particle._stillInvisible = false; // un-mark permanent invisibility
  53823. this._particleHasParent = (this._particle.parentId !== null);
  53824. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  53825. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  53826. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  53827. // particle rotation matrix
  53828. if (this.billboard) {
  53829. this._particle.rotation.x = 0.0;
  53830. this._particle.rotation.y = 0.0;
  53831. }
  53832. if (this._computeParticleRotation || this.billboard) {
  53833. if (this._particle.rotationQuaternion) {
  53834. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53835. }
  53836. else {
  53837. this._yaw = this._particle.rotation.y;
  53838. this._pitch = this._particle.rotation.x;
  53839. this._roll = this._particle.rotation.z;
  53840. this._quaternionRotationYPR();
  53841. }
  53842. this._quaternionToRotationMatrix();
  53843. }
  53844. if (this._particleHasParent) {
  53845. this._parent = this.particles[this._particle.parentId];
  53846. 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];
  53847. 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];
  53848. 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];
  53849. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  53850. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  53851. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  53852. if (this._computeParticleRotation || this.billboard) {
  53853. 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];
  53854. 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];
  53855. 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];
  53856. 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];
  53857. 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];
  53858. 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];
  53859. 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];
  53860. 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];
  53861. 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];
  53862. }
  53863. }
  53864. else {
  53865. this._particle._globalPosition.x = this._particle.position.x;
  53866. this._particle._globalPosition.y = this._particle.position.y;
  53867. this._particle._globalPosition.z = this._particle.position.z;
  53868. if (this._computeParticleRotation || this.billboard) {
  53869. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  53870. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  53871. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  53872. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  53873. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  53874. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  53875. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  53876. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  53877. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  53878. }
  53879. }
  53880. if (this._particle.translateFromPivot) {
  53881. this._pivotBackTranslation.x = 0.0;
  53882. this._pivotBackTranslation.y = 0.0;
  53883. this._pivotBackTranslation.z = 0.0;
  53884. }
  53885. else {
  53886. this._pivotBackTranslation.x = this._scaledPivot.x;
  53887. this._pivotBackTranslation.y = this._scaledPivot.y;
  53888. this._pivotBackTranslation.z = this._scaledPivot.z;
  53889. }
  53890. // particle vertex loop
  53891. for (pt = 0; pt < this._shape.length; pt++) {
  53892. idx = index + pt * 3;
  53893. colidx = colorIndex + pt * 4;
  53894. uvidx = uvIndex + pt * 2;
  53895. this._vertex.x = this._shape[pt].x;
  53896. this._vertex.y = this._shape[pt].y;
  53897. this._vertex.z = this._shape[pt].z;
  53898. if (this._computeParticleVertex) {
  53899. this.updateParticleVertex(this._particle, this._vertex, pt);
  53900. }
  53901. // positions
  53902. this._vertex.x *= this._particle.scaling.x;
  53903. this._vertex.y *= this._particle.scaling.y;
  53904. this._vertex.z *= this._particle.scaling.z;
  53905. this._vertex.x -= this._scaledPivot.x;
  53906. this._vertex.y -= this._scaledPivot.y;
  53907. this._vertex.z -= this._scaledPivot.z;
  53908. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53909. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53910. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53911. this._rotated.x += this._pivotBackTranslation.x;
  53912. this._rotated.y += this._pivotBackTranslation.y;
  53913. this._rotated.z += this._pivotBackTranslation.z;
  53914. 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;
  53915. 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;
  53916. 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;
  53917. if (this._computeBoundingBox) {
  53918. if (this._positions32[idx] < this._minimum.x) {
  53919. this._minimum.x = this._positions32[idx];
  53920. }
  53921. if (this._positions32[idx] > this._maximum.x) {
  53922. this._maximum.x = this._positions32[idx];
  53923. }
  53924. if (this._positions32[idx + 1] < this._minimum.y) {
  53925. this._minimum.y = this._positions32[idx + 1];
  53926. }
  53927. if (this._positions32[idx + 1] > this._maximum.y) {
  53928. this._maximum.y = this._positions32[idx + 1];
  53929. }
  53930. if (this._positions32[idx + 2] < this._minimum.z) {
  53931. this._minimum.z = this._positions32[idx + 2];
  53932. }
  53933. if (this._positions32[idx + 2] > this._maximum.z) {
  53934. this._maximum.z = this._positions32[idx + 2];
  53935. }
  53936. }
  53937. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  53938. if (!this._computeParticleVertex) {
  53939. this._normal.x = this._fixedNormal32[idx];
  53940. this._normal.y = this._fixedNormal32[idx + 1];
  53941. this._normal.z = this._fixedNormal32[idx + 2];
  53942. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  53943. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  53944. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  53945. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  53946. 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;
  53947. 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;
  53948. }
  53949. if (this._computeParticleColor && this._particle.color) {
  53950. this._colors32[colidx] = this._particle.color.r;
  53951. this._colors32[colidx + 1] = this._particle.color.g;
  53952. this._colors32[colidx + 2] = this._particle.color.b;
  53953. this._colors32[colidx + 3] = this._particle.color.a;
  53954. }
  53955. if (this._computeParticleTexture) {
  53956. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53957. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53958. }
  53959. }
  53960. }
  53961. else {
  53962. this._particle._stillInvisible = true; // mark the particle as invisible
  53963. for (pt = 0; pt < this._shape.length; pt++) {
  53964. idx = index + pt * 3;
  53965. colidx = colorIndex + pt * 4;
  53966. uvidx = uvIndex + pt * 2;
  53967. this._positions32[idx] = 0.0;
  53968. this._positions32[idx + 1] = 0.0;
  53969. this._positions32[idx + 2] = 0.0;
  53970. this._normals32[idx] = 0.0;
  53971. this._normals32[idx + 1] = 0.0;
  53972. this._normals32[idx + 2] = 0.0;
  53973. if (this._computeParticleColor && this._particle.color) {
  53974. this._colors32[colidx] = this._particle.color.r;
  53975. this._colors32[colidx + 1] = this._particle.color.g;
  53976. this._colors32[colidx + 2] = this._particle.color.b;
  53977. this._colors32[colidx + 3] = this._particle.color.a;
  53978. }
  53979. if (this._computeParticleTexture) {
  53980. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53981. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53982. }
  53983. }
  53984. }
  53985. // if the particle intersections must be computed : update the bbInfo
  53986. if (this._particlesIntersect) {
  53987. var bInfo = this._particle._boundingInfo;
  53988. var bBox = bInfo.boundingBox;
  53989. var bSphere = bInfo.boundingSphere;
  53990. if (!this._bSphereOnly) {
  53991. // place, scale and rotate the particle bbox within the SPS local system, then update it
  53992. for (var b = 0; b < bBox.vectors.length; b++) {
  53993. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  53994. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  53995. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  53996. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53997. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53998. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53999. 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;
  54000. 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;
  54001. 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;
  54002. }
  54003. bBox._update(this.mesh._worldMatrix);
  54004. }
  54005. // place and scale the particle bouding sphere in the SPS local system, then update it
  54006. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  54007. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  54008. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  54009. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  54010. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  54011. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  54012. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  54013. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  54014. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  54015. 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));
  54016. bSphere._update(this.mesh._worldMatrix);
  54017. }
  54018. // increment indexes for the next particle
  54019. index = idx + 3;
  54020. colorIndex = colidx + 4;
  54021. uvIndex = uvidx + 2;
  54022. }
  54023. // if the VBO must be updated
  54024. if (update) {
  54025. if (this._computeParticleColor) {
  54026. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  54027. }
  54028. if (this._computeParticleTexture) {
  54029. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  54030. }
  54031. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54032. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  54033. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  54034. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  54035. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  54036. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  54037. for (var i = 0; i < this._normals32.length; i++) {
  54038. this._fixedNormal32[i] = this._normals32[i];
  54039. }
  54040. }
  54041. if (!this.mesh.areNormalsFrozen) {
  54042. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  54043. }
  54044. }
  54045. if (this._depthSort && this._depthSortParticles) {
  54046. this.depthSortedParticles.sort(this._depthSortFunction);
  54047. var dspl = this.depthSortedParticles.length;
  54048. var sorted = 0;
  54049. var lind = 0;
  54050. var sind = 0;
  54051. var sid = 0;
  54052. for (sorted = 0; sorted < dspl; sorted++) {
  54053. lind = this.depthSortedParticles[sorted].indicesLength;
  54054. sind = this.depthSortedParticles[sorted].ind;
  54055. for (var i = 0; i < lind; i++) {
  54056. this._indices32[sid] = this._indices[sind + i];
  54057. sid++;
  54058. }
  54059. }
  54060. this.mesh.updateIndices(this._indices32);
  54061. }
  54062. }
  54063. if (this._computeBoundingBox) {
  54064. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  54065. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  54066. }
  54067. this.afterUpdateParticles(start, end, update);
  54068. return this;
  54069. };
  54070. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  54071. this._halfroll = this._roll * 0.5;
  54072. this._halfpitch = this._pitch * 0.5;
  54073. this._halfyaw = this._yaw * 0.5;
  54074. this._sinRoll = Math.sin(this._halfroll);
  54075. this._cosRoll = Math.cos(this._halfroll);
  54076. this._sinPitch = Math.sin(this._halfpitch);
  54077. this._cosPitch = Math.cos(this._halfpitch);
  54078. this._sinYaw = Math.sin(this._halfyaw);
  54079. this._cosYaw = Math.cos(this._halfyaw);
  54080. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  54081. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  54082. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  54083. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  54084. };
  54085. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  54086. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  54087. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  54088. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  54089. this._rotMatrix.m[3] = 0;
  54090. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  54091. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  54092. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  54093. this._rotMatrix.m[7] = 0;
  54094. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  54095. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  54096. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  54097. this._rotMatrix.m[11] = 0;
  54098. this._rotMatrix.m[12] = 0;
  54099. this._rotMatrix.m[13] = 0;
  54100. this._rotMatrix.m[14] = 0;
  54101. this._rotMatrix.m[15] = 1.0;
  54102. };
  54103. /**
  54104. * Disposes the SPS.
  54105. */
  54106. SolidParticleSystem.prototype.dispose = function () {
  54107. this.mesh.dispose();
  54108. this.vars = null;
  54109. // drop references to internal big arrays for the GC
  54110. this._positions = null;
  54111. this._indices = null;
  54112. this._normals = null;
  54113. this._uvs = null;
  54114. this._colors = null;
  54115. this._indices32 = null;
  54116. this._positions32 = null;
  54117. this._normals32 = null;
  54118. this._fixedNormal32 = null;
  54119. this._uvs32 = null;
  54120. this._colors32 = null;
  54121. this.pickedParticles = null;
  54122. };
  54123. /**
  54124. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  54125. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54126. * @returns the SPS.
  54127. */
  54128. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  54129. if (!this._isVisibilityBoxLocked) {
  54130. this.mesh.refreshBoundingInfo();
  54131. }
  54132. return this;
  54133. };
  54134. /**
  54135. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  54136. * @param size the size (float) of the visibility box
  54137. * note : this doesn't lock the SPS mesh bounding box.
  54138. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54139. */
  54140. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  54141. var vis = size / 2;
  54142. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  54143. };
  54144. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  54145. /**
  54146. * Gets whether the SPS as always visible or not
  54147. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54148. */
  54149. get: function () {
  54150. return this._alwaysVisible;
  54151. },
  54152. /**
  54153. * Sets the SPS as always visible or not
  54154. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54155. */
  54156. set: function (val) {
  54157. this._alwaysVisible = val;
  54158. this.mesh.alwaysSelectAsActiveMesh = val;
  54159. },
  54160. enumerable: true,
  54161. configurable: true
  54162. });
  54163. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  54164. /**
  54165. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54166. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54167. */
  54168. get: function () {
  54169. return this._isVisibilityBoxLocked;
  54170. },
  54171. /**
  54172. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54173. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54174. */
  54175. set: function (val) {
  54176. this._isVisibilityBoxLocked = val;
  54177. var boundingInfo = this.mesh.getBoundingInfo();
  54178. boundingInfo.isLocked = val;
  54179. },
  54180. enumerable: true,
  54181. configurable: true
  54182. });
  54183. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  54184. /**
  54185. * Gets if `setParticles()` computes the particle rotations or not.
  54186. * Default value : true. The SPS is faster when it's set to false.
  54187. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54188. */
  54189. get: function () {
  54190. return this._computeParticleRotation;
  54191. },
  54192. /**
  54193. * Tells to `setParticles()` to compute the particle rotations or not.
  54194. * Default value : true. The SPS is faster when it's set to false.
  54195. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54196. */
  54197. set: function (val) {
  54198. this._computeParticleRotation = val;
  54199. },
  54200. enumerable: true,
  54201. configurable: true
  54202. });
  54203. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  54204. /**
  54205. * Gets if `setParticles()` computes the particle colors or not.
  54206. * Default value : true. The SPS is faster when it's set to false.
  54207. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54208. */
  54209. get: function () {
  54210. return this._computeParticleColor;
  54211. },
  54212. /**
  54213. * Tells to `setParticles()` to compute the particle colors or not.
  54214. * Default value : true. The SPS is faster when it's set to false.
  54215. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54216. */
  54217. set: function (val) {
  54218. this._computeParticleColor = val;
  54219. },
  54220. enumerable: true,
  54221. configurable: true
  54222. });
  54223. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  54224. /**
  54225. * Gets if `setParticles()` computes the particle textures or not.
  54226. * Default value : true. The SPS is faster when it's set to false.
  54227. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  54228. */
  54229. get: function () {
  54230. return this._computeParticleTexture;
  54231. },
  54232. set: function (val) {
  54233. this._computeParticleTexture = val;
  54234. },
  54235. enumerable: true,
  54236. configurable: true
  54237. });
  54238. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  54239. /**
  54240. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  54241. * Default value : false. The SPS is faster when it's set to false.
  54242. * Note : the particle custom vertex positions aren't stored values.
  54243. */
  54244. get: function () {
  54245. return this._computeParticleVertex;
  54246. },
  54247. /**
  54248. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  54249. * Default value : false. The SPS is faster when it's set to false.
  54250. * Note : the particle custom vertex positions aren't stored values.
  54251. */
  54252. set: function (val) {
  54253. this._computeParticleVertex = val;
  54254. },
  54255. enumerable: true,
  54256. configurable: true
  54257. });
  54258. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  54259. /**
  54260. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  54261. */
  54262. get: function () {
  54263. return this._computeBoundingBox;
  54264. },
  54265. /**
  54266. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  54267. */
  54268. set: function (val) {
  54269. this._computeBoundingBox = val;
  54270. },
  54271. enumerable: true,
  54272. configurable: true
  54273. });
  54274. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  54275. /**
  54276. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  54277. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  54278. * Default : `true`
  54279. */
  54280. get: function () {
  54281. return this._depthSortParticles;
  54282. },
  54283. /**
  54284. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  54285. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  54286. * Default : `true`
  54287. */
  54288. set: function (val) {
  54289. this._depthSortParticles = val;
  54290. },
  54291. enumerable: true,
  54292. configurable: true
  54293. });
  54294. // =======================================================================
  54295. // Particle behavior logic
  54296. // these following methods may be overwritten by the user to fit his needs
  54297. /**
  54298. * This function does nothing. It may be overwritten to set all the particle first values.
  54299. * The SPS doesn't call this function, you may have to call it by your own.
  54300. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54301. */
  54302. SolidParticleSystem.prototype.initParticles = function () {
  54303. };
  54304. /**
  54305. * This function does nothing. It may be overwritten to recycle a particle.
  54306. * The SPS doesn't call this function, you may have to call it by your own.
  54307. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54308. * @param particle The particle to recycle
  54309. * @returns the recycled particle
  54310. */
  54311. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  54312. return particle;
  54313. };
  54314. /**
  54315. * Updates a particle : this function should be overwritten by the user.
  54316. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  54317. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54318. * @example : just set a particle position or velocity and recycle conditions
  54319. * @param particle The particle to update
  54320. * @returns the updated particle
  54321. */
  54322. SolidParticleSystem.prototype.updateParticle = function (particle) {
  54323. return particle;
  54324. };
  54325. /**
  54326. * Updates a vertex of a particle : it can be overwritten by the user.
  54327. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  54328. * @param particle the current particle
  54329. * @param vertex the current index of the current particle
  54330. * @param pt the index of the current vertex in the particle shape
  54331. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  54332. * @example : just set a vertex particle position
  54333. * @returns the updated vertex
  54334. */
  54335. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  54336. return vertex;
  54337. };
  54338. /**
  54339. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  54340. * This does nothing and may be overwritten by the user.
  54341. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54342. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54343. * @param update the boolean update value actually passed to setParticles()
  54344. */
  54345. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  54346. };
  54347. /**
  54348. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  54349. * This will be passed three parameters.
  54350. * This does nothing and may be overwritten by the user.
  54351. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54352. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54353. * @param update the boolean update value actually passed to setParticles()
  54354. */
  54355. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  54356. };
  54357. return SolidParticleSystem;
  54358. }());
  54359. BABYLON.SolidParticleSystem = SolidParticleSystem;
  54360. })(BABYLON || (BABYLON = {}));
  54361. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  54362. "use strict";
  54363. var BABYLON;
  54364. (function (BABYLON) {
  54365. var ShaderMaterial = /** @class */ (function (_super) {
  54366. __extends(ShaderMaterial, _super);
  54367. function ShaderMaterial(name, scene, shaderPath, options) {
  54368. var _this = _super.call(this, name, scene) || this;
  54369. _this._textures = {};
  54370. _this._textureArrays = {};
  54371. _this._floats = {};
  54372. _this._ints = {};
  54373. _this._floatsArrays = {};
  54374. _this._colors3 = {};
  54375. _this._colors3Arrays = {};
  54376. _this._colors4 = {};
  54377. _this._vectors2 = {};
  54378. _this._vectors3 = {};
  54379. _this._vectors4 = {};
  54380. _this._matrices = {};
  54381. _this._matrices3x3 = {};
  54382. _this._matrices2x2 = {};
  54383. _this._vectors2Arrays = {};
  54384. _this._vectors3Arrays = {};
  54385. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  54386. _this._shaderPath = shaderPath;
  54387. options.needAlphaBlending = options.needAlphaBlending || false;
  54388. options.needAlphaTesting = options.needAlphaTesting || false;
  54389. options.attributes = options.attributes || ["position", "normal", "uv"];
  54390. options.uniforms = options.uniforms || ["worldViewProjection"];
  54391. options.uniformBuffers = options.uniformBuffers || [];
  54392. options.samplers = options.samplers || [];
  54393. options.defines = options.defines || [];
  54394. _this._options = options;
  54395. return _this;
  54396. }
  54397. ShaderMaterial.prototype.getClassName = function () {
  54398. return "ShaderMaterial";
  54399. };
  54400. ShaderMaterial.prototype.needAlphaBlending = function () {
  54401. return this._options.needAlphaBlending;
  54402. };
  54403. ShaderMaterial.prototype.needAlphaTesting = function () {
  54404. return this._options.needAlphaTesting;
  54405. };
  54406. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  54407. if (this._options.uniforms.indexOf(uniformName) === -1) {
  54408. this._options.uniforms.push(uniformName);
  54409. }
  54410. };
  54411. ShaderMaterial.prototype.setTexture = function (name, texture) {
  54412. if (this._options.samplers.indexOf(name) === -1) {
  54413. this._options.samplers.push(name);
  54414. }
  54415. this._textures[name] = texture;
  54416. return this;
  54417. };
  54418. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  54419. if (this._options.samplers.indexOf(name) === -1) {
  54420. this._options.samplers.push(name);
  54421. }
  54422. this._checkUniform(name);
  54423. this._textureArrays[name] = textures;
  54424. return this;
  54425. };
  54426. ShaderMaterial.prototype.setFloat = function (name, value) {
  54427. this._checkUniform(name);
  54428. this._floats[name] = value;
  54429. return this;
  54430. };
  54431. ShaderMaterial.prototype.setInt = function (name, value) {
  54432. this._checkUniform(name);
  54433. this._ints[name] = value;
  54434. return this;
  54435. };
  54436. ShaderMaterial.prototype.setFloats = function (name, value) {
  54437. this._checkUniform(name);
  54438. this._floatsArrays[name] = value;
  54439. return this;
  54440. };
  54441. ShaderMaterial.prototype.setColor3 = function (name, value) {
  54442. this._checkUniform(name);
  54443. this._colors3[name] = value;
  54444. return this;
  54445. };
  54446. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  54447. this._checkUniform(name);
  54448. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  54449. color.toArray(arr, arr.length);
  54450. return arr;
  54451. }, []);
  54452. return this;
  54453. };
  54454. ShaderMaterial.prototype.setColor4 = function (name, value) {
  54455. this._checkUniform(name);
  54456. this._colors4[name] = value;
  54457. return this;
  54458. };
  54459. ShaderMaterial.prototype.setVector2 = function (name, value) {
  54460. this._checkUniform(name);
  54461. this._vectors2[name] = value;
  54462. return this;
  54463. };
  54464. ShaderMaterial.prototype.setVector3 = function (name, value) {
  54465. this._checkUniform(name);
  54466. this._vectors3[name] = value;
  54467. return this;
  54468. };
  54469. ShaderMaterial.prototype.setVector4 = function (name, value) {
  54470. this._checkUniform(name);
  54471. this._vectors4[name] = value;
  54472. return this;
  54473. };
  54474. ShaderMaterial.prototype.setMatrix = function (name, value) {
  54475. this._checkUniform(name);
  54476. this._matrices[name] = value;
  54477. return this;
  54478. };
  54479. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  54480. this._checkUniform(name);
  54481. this._matrices3x3[name] = value;
  54482. return this;
  54483. };
  54484. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  54485. this._checkUniform(name);
  54486. this._matrices2x2[name] = value;
  54487. return this;
  54488. };
  54489. ShaderMaterial.prototype.setArray2 = function (name, value) {
  54490. this._checkUniform(name);
  54491. this._vectors2Arrays[name] = value;
  54492. return this;
  54493. };
  54494. ShaderMaterial.prototype.setArray3 = function (name, value) {
  54495. this._checkUniform(name);
  54496. this._vectors3Arrays[name] = value;
  54497. return this;
  54498. };
  54499. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  54500. if (!mesh) {
  54501. return true;
  54502. }
  54503. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  54504. return false;
  54505. }
  54506. return false;
  54507. };
  54508. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  54509. var scene = this.getScene();
  54510. var engine = scene.getEngine();
  54511. if (!this.checkReadyOnEveryCall) {
  54512. if (this._renderId === scene.getRenderId()) {
  54513. if (this._checkCache(scene, mesh, useInstances)) {
  54514. return true;
  54515. }
  54516. }
  54517. }
  54518. // Instances
  54519. var defines = [];
  54520. var attribs = [];
  54521. var fallbacks = new BABYLON.EffectFallbacks();
  54522. if (useInstances) {
  54523. defines.push("#define INSTANCES");
  54524. }
  54525. for (var index = 0; index < this._options.defines.length; index++) {
  54526. defines.push(this._options.defines[index]);
  54527. }
  54528. for (var index = 0; index < this._options.attributes.length; index++) {
  54529. attribs.push(this._options.attributes[index]);
  54530. }
  54531. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  54532. attribs.push(BABYLON.VertexBuffer.ColorKind);
  54533. defines.push("#define VERTEXCOLOR");
  54534. }
  54535. // Bones
  54536. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  54537. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  54538. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  54539. if (mesh.numBoneInfluencers > 4) {
  54540. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  54541. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  54542. }
  54543. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  54544. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  54545. fallbacks.addCPUSkinningFallback(0, mesh);
  54546. if (this._options.uniforms.indexOf("mBones") === -1) {
  54547. this._options.uniforms.push("mBones");
  54548. }
  54549. }
  54550. else {
  54551. defines.push("#define NUM_BONE_INFLUENCERS 0");
  54552. }
  54553. // Textures
  54554. for (var name in this._textures) {
  54555. if (!this._textures[name].isReady()) {
  54556. return false;
  54557. }
  54558. }
  54559. // Alpha test
  54560. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  54561. defines.push("#define ALPHATEST");
  54562. }
  54563. var previousEffect = this._effect;
  54564. var join = defines.join("\n");
  54565. this._effect = engine.createEffect(this._shaderPath, {
  54566. attributes: attribs,
  54567. uniformsNames: this._options.uniforms,
  54568. uniformBuffersNames: this._options.uniformBuffers,
  54569. samplers: this._options.samplers,
  54570. defines: join,
  54571. fallbacks: fallbacks,
  54572. onCompiled: this.onCompiled,
  54573. onError: this.onError
  54574. }, engine);
  54575. if (!this._effect.isReady()) {
  54576. return false;
  54577. }
  54578. if (previousEffect !== this._effect) {
  54579. scene.resetCachedMaterial();
  54580. }
  54581. this._renderId = scene.getRenderId();
  54582. return true;
  54583. };
  54584. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  54585. var scene = this.getScene();
  54586. if (!this._effect) {
  54587. return;
  54588. }
  54589. if (this._options.uniforms.indexOf("world") !== -1) {
  54590. this._effect.setMatrix("world", world);
  54591. }
  54592. if (this._options.uniforms.indexOf("worldView") !== -1) {
  54593. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  54594. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  54595. }
  54596. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  54597. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  54598. }
  54599. };
  54600. ShaderMaterial.prototype.bind = function (world, mesh) {
  54601. // Std values
  54602. this.bindOnlyWorldMatrix(world);
  54603. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  54604. if (this._options.uniforms.indexOf("view") !== -1) {
  54605. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  54606. }
  54607. if (this._options.uniforms.indexOf("projection") !== -1) {
  54608. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  54609. }
  54610. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  54611. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  54612. }
  54613. // Bones
  54614. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  54615. var name;
  54616. // Texture
  54617. for (name in this._textures) {
  54618. this._effect.setTexture(name, this._textures[name]);
  54619. }
  54620. // Texture arrays
  54621. for (name in this._textureArrays) {
  54622. this._effect.setTextureArray(name, this._textureArrays[name]);
  54623. }
  54624. // Int
  54625. for (name in this._ints) {
  54626. this._effect.setInt(name, this._ints[name]);
  54627. }
  54628. // Float
  54629. for (name in this._floats) {
  54630. this._effect.setFloat(name, this._floats[name]);
  54631. }
  54632. // Floats
  54633. for (name in this._floatsArrays) {
  54634. this._effect.setArray(name, this._floatsArrays[name]);
  54635. }
  54636. // Color3
  54637. for (name in this._colors3) {
  54638. this._effect.setColor3(name, this._colors3[name]);
  54639. }
  54640. for (name in this._colors3Arrays) {
  54641. this._effect.setArray3(name, this._colors3Arrays[name]);
  54642. }
  54643. // Color4
  54644. for (name in this._colors4) {
  54645. var color = this._colors4[name];
  54646. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  54647. }
  54648. // Vector2
  54649. for (name in this._vectors2) {
  54650. this._effect.setVector2(name, this._vectors2[name]);
  54651. }
  54652. // Vector3
  54653. for (name in this._vectors3) {
  54654. this._effect.setVector3(name, this._vectors3[name]);
  54655. }
  54656. // Vector4
  54657. for (name in this._vectors4) {
  54658. this._effect.setVector4(name, this._vectors4[name]);
  54659. }
  54660. // Matrix
  54661. for (name in this._matrices) {
  54662. this._effect.setMatrix(name, this._matrices[name]);
  54663. }
  54664. // Matrix 3x3
  54665. for (name in this._matrices3x3) {
  54666. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  54667. }
  54668. // Matrix 2x2
  54669. for (name in this._matrices2x2) {
  54670. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  54671. }
  54672. // Vector2Array
  54673. for (name in this._vectors2Arrays) {
  54674. this._effect.setArray2(name, this._vectors2Arrays[name]);
  54675. }
  54676. // Vector3Array
  54677. for (name in this._vectors3Arrays) {
  54678. this._effect.setArray3(name, this._vectors3Arrays[name]);
  54679. }
  54680. }
  54681. this._afterBind(mesh);
  54682. };
  54683. ShaderMaterial.prototype.getActiveTextures = function () {
  54684. var activeTextures = _super.prototype.getActiveTextures.call(this);
  54685. for (var name in this._textures) {
  54686. activeTextures.push(this._textures[name]);
  54687. }
  54688. for (var name in this._textureArrays) {
  54689. var array = this._textureArrays[name];
  54690. for (var index = 0; index < array.length; index++) {
  54691. activeTextures.push(array[index]);
  54692. }
  54693. }
  54694. return activeTextures;
  54695. };
  54696. ShaderMaterial.prototype.hasTexture = function (texture) {
  54697. if (_super.prototype.hasTexture.call(this, texture)) {
  54698. return true;
  54699. }
  54700. for (var name in this._textures) {
  54701. if (this._textures[name] === texture) {
  54702. return true;
  54703. }
  54704. }
  54705. for (var name in this._textureArrays) {
  54706. var array = this._textureArrays[name];
  54707. for (var index = 0; index < array.length; index++) {
  54708. if (array[index] === texture) {
  54709. return true;
  54710. }
  54711. }
  54712. }
  54713. return false;
  54714. };
  54715. ShaderMaterial.prototype.clone = function (name) {
  54716. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  54717. return newShaderMaterial;
  54718. };
  54719. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  54720. if (forceDisposeTextures) {
  54721. var name;
  54722. for (name in this._textures) {
  54723. this._textures[name].dispose();
  54724. }
  54725. for (name in this._textureArrays) {
  54726. var array = this._textureArrays[name];
  54727. for (var index = 0; index < array.length; index++) {
  54728. array[index].dispose();
  54729. }
  54730. }
  54731. }
  54732. this._textures = {};
  54733. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54734. };
  54735. ShaderMaterial.prototype.serialize = function () {
  54736. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54737. serializationObject.customType = "BABYLON.ShaderMaterial";
  54738. serializationObject.options = this._options;
  54739. serializationObject.shaderPath = this._shaderPath;
  54740. var name;
  54741. // Texture
  54742. serializationObject.textures = {};
  54743. for (name in this._textures) {
  54744. serializationObject.textures[name] = this._textures[name].serialize();
  54745. }
  54746. // Texture arrays
  54747. serializationObject.textureArrays = {};
  54748. for (name in this._textureArrays) {
  54749. serializationObject.textureArrays[name] = [];
  54750. var array = this._textureArrays[name];
  54751. for (var index = 0; index < array.length; index++) {
  54752. serializationObject.textureArrays[name].push(array[index].serialize());
  54753. }
  54754. }
  54755. // Float
  54756. serializationObject.floats = {};
  54757. for (name in this._floats) {
  54758. serializationObject.floats[name] = this._floats[name];
  54759. }
  54760. // Float s
  54761. serializationObject.FloatArrays = {};
  54762. for (name in this._floatsArrays) {
  54763. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  54764. }
  54765. // Color3
  54766. serializationObject.colors3 = {};
  54767. for (name in this._colors3) {
  54768. serializationObject.colors3[name] = this._colors3[name].asArray();
  54769. }
  54770. // Color3 array
  54771. serializationObject.colors3Arrays = {};
  54772. for (name in this._colors3Arrays) {
  54773. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  54774. }
  54775. // Color4
  54776. serializationObject.colors4 = {};
  54777. for (name in this._colors4) {
  54778. serializationObject.colors4[name] = this._colors4[name].asArray();
  54779. }
  54780. // Vector2
  54781. serializationObject.vectors2 = {};
  54782. for (name in this._vectors2) {
  54783. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  54784. }
  54785. // Vector3
  54786. serializationObject.vectors3 = {};
  54787. for (name in this._vectors3) {
  54788. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  54789. }
  54790. // Vector4
  54791. serializationObject.vectors4 = {};
  54792. for (name in this._vectors4) {
  54793. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  54794. }
  54795. // Matrix
  54796. serializationObject.matrices = {};
  54797. for (name in this._matrices) {
  54798. serializationObject.matrices[name] = this._matrices[name].asArray();
  54799. }
  54800. // Matrix 3x3
  54801. serializationObject.matrices3x3 = {};
  54802. for (name in this._matrices3x3) {
  54803. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  54804. }
  54805. // Matrix 2x2
  54806. serializationObject.matrices2x2 = {};
  54807. for (name in this._matrices2x2) {
  54808. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  54809. }
  54810. // Vector2Array
  54811. serializationObject.vectors2Arrays = {};
  54812. for (name in this._vectors2Arrays) {
  54813. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  54814. }
  54815. // Vector3Array
  54816. serializationObject.vectors3Arrays = {};
  54817. for (name in this._vectors3Arrays) {
  54818. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  54819. }
  54820. return serializationObject;
  54821. };
  54822. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  54823. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  54824. var name;
  54825. // Texture
  54826. for (name in source.textures) {
  54827. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  54828. }
  54829. // Texture arrays
  54830. for (name in source.textureArrays) {
  54831. var array = source.textureArrays[name];
  54832. var textureArray = new Array();
  54833. for (var index = 0; index < array.length; index++) {
  54834. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  54835. }
  54836. material.setTextureArray(name, textureArray);
  54837. }
  54838. // Float
  54839. for (name in source.floats) {
  54840. material.setFloat(name, source.floats[name]);
  54841. }
  54842. // Float s
  54843. for (name in source.floatsArrays) {
  54844. material.setFloats(name, source.floatsArrays[name]);
  54845. }
  54846. // Color3
  54847. for (name in source.colors3) {
  54848. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  54849. }
  54850. // Color3 arrays
  54851. for (name in source.colors3Arrays) {
  54852. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  54853. if (i % 3 === 0) {
  54854. arr.push([num]);
  54855. }
  54856. else {
  54857. arr[arr.length - 1].push(num);
  54858. }
  54859. return arr;
  54860. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  54861. material.setColor3Array(name, colors);
  54862. }
  54863. // Color4
  54864. for (name in source.colors4) {
  54865. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  54866. }
  54867. // Vector2
  54868. for (name in source.vectors2) {
  54869. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  54870. }
  54871. // Vector3
  54872. for (name in source.vectors3) {
  54873. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  54874. }
  54875. // Vector4
  54876. for (name in source.vectors4) {
  54877. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  54878. }
  54879. // Matrix
  54880. for (name in source.matrices) {
  54881. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  54882. }
  54883. // Matrix 3x3
  54884. for (name in source.matrices3x3) {
  54885. material.setMatrix3x3(name, source.matrices3x3[name]);
  54886. }
  54887. // Matrix 2x2
  54888. for (name in source.matrices2x2) {
  54889. material.setMatrix2x2(name, source.matrices2x2[name]);
  54890. }
  54891. // Vector2Array
  54892. for (name in source.vectors2Arrays) {
  54893. material.setArray2(name, source.vectors2Arrays[name]);
  54894. }
  54895. // Vector3Array
  54896. for (name in source.vectors3Arrays) {
  54897. material.setArray3(name, source.vectors3Arrays[name]);
  54898. }
  54899. return material;
  54900. };
  54901. return ShaderMaterial;
  54902. }(BABYLON.Material));
  54903. BABYLON.ShaderMaterial = ShaderMaterial;
  54904. })(BABYLON || (BABYLON = {}));
  54905. //# sourceMappingURL=babylon.shaderMaterial.js.map
  54906. "use strict";
  54907. var BABYLON;
  54908. (function (BABYLON) {
  54909. var GroundMesh = /** @class */ (function (_super) {
  54910. __extends(GroundMesh, _super);
  54911. function GroundMesh(name, scene) {
  54912. var _this = _super.call(this, name, scene) || this;
  54913. _this.generateOctree = false;
  54914. return _this;
  54915. }
  54916. GroundMesh.prototype.getClassName = function () {
  54917. return "GroundMesh";
  54918. };
  54919. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  54920. get: function () {
  54921. return Math.min(this._subdivisionsX, this._subdivisionsY);
  54922. },
  54923. enumerable: true,
  54924. configurable: true
  54925. });
  54926. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  54927. get: function () {
  54928. return this._subdivisionsX;
  54929. },
  54930. enumerable: true,
  54931. configurable: true
  54932. });
  54933. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  54934. get: function () {
  54935. return this._subdivisionsY;
  54936. },
  54937. enumerable: true,
  54938. configurable: true
  54939. });
  54940. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  54941. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  54942. this._subdivisionsX = chunksCount;
  54943. this._subdivisionsY = chunksCount;
  54944. this.subdivide(chunksCount);
  54945. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  54946. };
  54947. /**
  54948. * Returns a height (y) value in the Worl system :
  54949. * the ground altitude at the coordinates (x, z) expressed in the World system.
  54950. * Returns the ground y position if (x, z) are outside the ground surface.
  54951. */
  54952. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  54953. var world = this.getWorldMatrix();
  54954. var invMat = BABYLON.Tmp.Matrix[5];
  54955. world.invertToRef(invMat);
  54956. var tmpVect = BABYLON.Tmp.Vector3[8];
  54957. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  54958. x = tmpVect.x;
  54959. z = tmpVect.z;
  54960. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54961. return this.position.y;
  54962. }
  54963. if (!this._heightQuads || this._heightQuads.length == 0) {
  54964. this._initHeightQuads();
  54965. this._computeHeightQuads();
  54966. }
  54967. var facet = this._getFacetAt(x, z);
  54968. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  54969. // return y in the World system
  54970. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  54971. return tmpVect.y;
  54972. };
  54973. /**
  54974. * Returns a normalized vector (Vector3) orthogonal to the ground
  54975. * at the ground coordinates (x, z) expressed in the World system.
  54976. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  54977. */
  54978. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  54979. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  54980. this.getNormalAtCoordinatesToRef(x, z, normal);
  54981. return normal;
  54982. };
  54983. /**
  54984. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  54985. * at the ground coordinates (x, z) expressed in the World system.
  54986. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  54987. * Returns the GroundMesh.
  54988. */
  54989. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  54990. var world = this.getWorldMatrix();
  54991. var tmpMat = BABYLON.Tmp.Matrix[5];
  54992. world.invertToRef(tmpMat);
  54993. var tmpVect = BABYLON.Tmp.Vector3[8];
  54994. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  54995. x = tmpVect.x;
  54996. z = tmpVect.z;
  54997. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54998. return this;
  54999. }
  55000. if (!this._heightQuads || this._heightQuads.length == 0) {
  55001. this._initHeightQuads();
  55002. this._computeHeightQuads();
  55003. }
  55004. var facet = this._getFacetAt(x, z);
  55005. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  55006. return this;
  55007. };
  55008. /**
  55009. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  55010. * if the ground has been updated.
  55011. * This can be used in the render loop.
  55012. * Returns the GroundMesh.
  55013. */
  55014. GroundMesh.prototype.updateCoordinateHeights = function () {
  55015. if (!this._heightQuads || this._heightQuads.length == 0) {
  55016. this._initHeightQuads();
  55017. }
  55018. this._computeHeightQuads();
  55019. return this;
  55020. };
  55021. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  55022. GroundMesh.prototype._getFacetAt = function (x, z) {
  55023. // retrieve col and row from x, z coordinates in the ground local system
  55024. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  55025. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  55026. var quad = this._heightQuads[row * this._subdivisionsX + col];
  55027. var facet;
  55028. if (z < quad.slope.x * x + quad.slope.y) {
  55029. facet = quad.facet1;
  55030. }
  55031. else {
  55032. facet = quad.facet2;
  55033. }
  55034. return facet;
  55035. };
  55036. // Creates and populates the heightMap array with "facet" elements :
  55037. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  55038. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55039. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55040. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55041. // Returns the GroundMesh.
  55042. GroundMesh.prototype._initHeightQuads = function () {
  55043. var subdivisionsX = this._subdivisionsX;
  55044. var subdivisionsY = this._subdivisionsY;
  55045. this._heightQuads = new Array();
  55046. for (var row = 0; row < subdivisionsY; row++) {
  55047. for (var col = 0; col < subdivisionsX; col++) {
  55048. 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) };
  55049. this._heightQuads[row * subdivisionsX + col] = quad;
  55050. }
  55051. }
  55052. return this;
  55053. };
  55054. // Compute each quad element values and update the the heightMap array :
  55055. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55056. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55057. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55058. // Returns the GroundMesh.
  55059. GroundMesh.prototype._computeHeightQuads = function () {
  55060. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55061. if (!positions) {
  55062. return this;
  55063. }
  55064. var v1 = BABYLON.Tmp.Vector3[3];
  55065. var v2 = BABYLON.Tmp.Vector3[2];
  55066. var v3 = BABYLON.Tmp.Vector3[1];
  55067. var v4 = BABYLON.Tmp.Vector3[0];
  55068. var v1v2 = BABYLON.Tmp.Vector3[4];
  55069. var v1v3 = BABYLON.Tmp.Vector3[5];
  55070. var v1v4 = BABYLON.Tmp.Vector3[6];
  55071. var norm1 = BABYLON.Tmp.Vector3[7];
  55072. var norm2 = BABYLON.Tmp.Vector3[8];
  55073. var i = 0;
  55074. var j = 0;
  55075. var k = 0;
  55076. var cd = 0; // 2D slope coefficient : z = cd * x + h
  55077. var h = 0;
  55078. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  55079. var d2 = 0;
  55080. var subdivisionsX = this._subdivisionsX;
  55081. var subdivisionsY = this._subdivisionsY;
  55082. for (var row = 0; row < subdivisionsY; row++) {
  55083. for (var col = 0; col < subdivisionsX; col++) {
  55084. i = col * 3;
  55085. j = row * (subdivisionsX + 1) * 3;
  55086. k = (row + 1) * (subdivisionsX + 1) * 3;
  55087. v1.x = positions[j + i];
  55088. v1.y = positions[j + i + 1];
  55089. v1.z = positions[j + i + 2];
  55090. v2.x = positions[j + i + 3];
  55091. v2.y = positions[j + i + 4];
  55092. v2.z = positions[j + i + 5];
  55093. v3.x = positions[k + i];
  55094. v3.y = positions[k + i + 1];
  55095. v3.z = positions[k + i + 2];
  55096. v4.x = positions[k + i + 3];
  55097. v4.y = positions[k + i + 4];
  55098. v4.z = positions[k + i + 5];
  55099. // 2D slope V1V4
  55100. cd = (v4.z - v1.z) / (v4.x - v1.x);
  55101. h = v1.z - cd * v1.x; // v1 belongs to the slope
  55102. // facet equations :
  55103. // we compute each facet normal vector
  55104. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  55105. // we compute the value d by applying the equation to v1 which belongs to the plane
  55106. // then we store the facet equation in a Vector4
  55107. v2.subtractToRef(v1, v1v2);
  55108. v3.subtractToRef(v1, v1v3);
  55109. v4.subtractToRef(v1, v1v4);
  55110. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  55111. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  55112. norm1.normalize();
  55113. norm2.normalize();
  55114. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  55115. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  55116. var quad = this._heightQuads[row * subdivisionsX + col];
  55117. quad.slope.copyFromFloats(cd, h);
  55118. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  55119. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  55120. }
  55121. }
  55122. return this;
  55123. };
  55124. GroundMesh.prototype.serialize = function (serializationObject) {
  55125. _super.prototype.serialize.call(this, serializationObject);
  55126. serializationObject.subdivisionsX = this._subdivisionsX;
  55127. serializationObject.subdivisionsY = this._subdivisionsY;
  55128. serializationObject.minX = this._minX;
  55129. serializationObject.maxX = this._maxX;
  55130. serializationObject.minZ = this._minZ;
  55131. serializationObject.maxZ = this._maxZ;
  55132. serializationObject.width = this._width;
  55133. serializationObject.height = this._height;
  55134. };
  55135. GroundMesh.Parse = function (parsedMesh, scene) {
  55136. var result = new GroundMesh(parsedMesh.name, scene);
  55137. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  55138. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  55139. result._minX = parsedMesh.minX;
  55140. result._maxX = parsedMesh.maxX;
  55141. result._minZ = parsedMesh.minZ;
  55142. result._maxZ = parsedMesh.maxZ;
  55143. result._width = parsedMesh.width;
  55144. result._height = parsedMesh.height;
  55145. return result;
  55146. };
  55147. return GroundMesh;
  55148. }(BABYLON.Mesh));
  55149. BABYLON.GroundMesh = GroundMesh;
  55150. })(BABYLON || (BABYLON = {}));
  55151. //# sourceMappingURL=babylon.groundMesh.js.map
  55152. "use strict";
  55153. var BABYLON;
  55154. (function (BABYLON) {
  55155. /**
  55156. * Creates an instance based on a source mesh.
  55157. */
  55158. var InstancedMesh = /** @class */ (function (_super) {
  55159. __extends(InstancedMesh, _super);
  55160. function InstancedMesh(name, source) {
  55161. var _this = _super.call(this, name, source.getScene()) || this;
  55162. source.instances.push(_this);
  55163. _this._sourceMesh = source;
  55164. _this.position.copyFrom(source.position);
  55165. _this.rotation.copyFrom(source.rotation);
  55166. _this.scaling.copyFrom(source.scaling);
  55167. if (source.rotationQuaternion) {
  55168. _this.rotationQuaternion = source.rotationQuaternion.clone();
  55169. }
  55170. _this.infiniteDistance = source.infiniteDistance;
  55171. _this.setPivotMatrix(source.getPivotMatrix());
  55172. _this.refreshBoundingInfo();
  55173. _this._syncSubMeshes();
  55174. return _this;
  55175. }
  55176. /**
  55177. * Returns the string "InstancedMesh".
  55178. */
  55179. InstancedMesh.prototype.getClassName = function () {
  55180. return "InstancedMesh";
  55181. };
  55182. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  55183. // Methods
  55184. get: function () {
  55185. return this._sourceMesh.receiveShadows;
  55186. },
  55187. enumerable: true,
  55188. configurable: true
  55189. });
  55190. Object.defineProperty(InstancedMesh.prototype, "material", {
  55191. get: function () {
  55192. return this._sourceMesh.material;
  55193. },
  55194. enumerable: true,
  55195. configurable: true
  55196. });
  55197. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  55198. get: function () {
  55199. return this._sourceMesh.visibility;
  55200. },
  55201. enumerable: true,
  55202. configurable: true
  55203. });
  55204. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  55205. get: function () {
  55206. return this._sourceMesh.skeleton;
  55207. },
  55208. enumerable: true,
  55209. configurable: true
  55210. });
  55211. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  55212. get: function () {
  55213. return this._sourceMesh.renderingGroupId;
  55214. },
  55215. set: function (value) {
  55216. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  55217. return;
  55218. }
  55219. //no-op with warning
  55220. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  55221. },
  55222. enumerable: true,
  55223. configurable: true
  55224. });
  55225. /**
  55226. * Returns the total number of vertices (integer).
  55227. */
  55228. InstancedMesh.prototype.getTotalVertices = function () {
  55229. return this._sourceMesh.getTotalVertices();
  55230. };
  55231. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  55232. get: function () {
  55233. return this._sourceMesh;
  55234. },
  55235. enumerable: true,
  55236. configurable: true
  55237. });
  55238. /**
  55239. * Is this node ready to be used/rendered
  55240. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  55241. * @return {boolean} is it ready
  55242. */
  55243. InstancedMesh.prototype.isReady = function (completeCheck) {
  55244. if (completeCheck === void 0) { completeCheck = false; }
  55245. return this._sourceMesh.isReady(completeCheck, true);
  55246. };
  55247. /**
  55248. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  55249. */
  55250. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  55251. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  55252. };
  55253. /**
  55254. * Sets the vertex data of the mesh geometry for the requested `kind`.
  55255. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  55256. * The `data` are either a numeric array either a Float32Array.
  55257. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  55258. * 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).
  55259. * Note that a new underlying VertexBuffer object is created each call.
  55260. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  55261. *
  55262. * Possible `kind` values :
  55263. * - BABYLON.VertexBuffer.PositionKind
  55264. * - BABYLON.VertexBuffer.UVKind
  55265. * - BABYLON.VertexBuffer.UV2Kind
  55266. * - BABYLON.VertexBuffer.UV3Kind
  55267. * - BABYLON.VertexBuffer.UV4Kind
  55268. * - BABYLON.VertexBuffer.UV5Kind
  55269. * - BABYLON.VertexBuffer.UV6Kind
  55270. * - BABYLON.VertexBuffer.ColorKind
  55271. * - BABYLON.VertexBuffer.MatricesIndicesKind
  55272. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  55273. * - BABYLON.VertexBuffer.MatricesWeightsKind
  55274. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  55275. *
  55276. * Returns the Mesh.
  55277. */
  55278. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  55279. if (this.sourceMesh) {
  55280. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  55281. }
  55282. return this.sourceMesh;
  55283. };
  55284. /**
  55285. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  55286. * If the mesh has no geometry, it is simply returned as it is.
  55287. * The `data` are either a numeric array either a Float32Array.
  55288. * No new underlying VertexBuffer object is created.
  55289. * 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.
  55290. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  55291. *
  55292. * Possible `kind` values :
  55293. * - BABYLON.VertexBuffer.PositionKind
  55294. * - BABYLON.VertexBuffer.UVKind
  55295. * - BABYLON.VertexBuffer.UV2Kind
  55296. * - BABYLON.VertexBuffer.UV3Kind
  55297. * - BABYLON.VertexBuffer.UV4Kind
  55298. * - BABYLON.VertexBuffer.UV5Kind
  55299. * - BABYLON.VertexBuffer.UV6Kind
  55300. * - BABYLON.VertexBuffer.ColorKind
  55301. * - BABYLON.VertexBuffer.MatricesIndicesKind
  55302. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  55303. * - BABYLON.VertexBuffer.MatricesWeightsKind
  55304. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  55305. *
  55306. * Returns the Mesh.
  55307. */
  55308. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  55309. if (this.sourceMesh) {
  55310. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  55311. }
  55312. return this.sourceMesh;
  55313. };
  55314. /**
  55315. * Sets the mesh indices.
  55316. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  55317. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  55318. * This method creates a new index buffer each call.
  55319. * Returns the Mesh.
  55320. */
  55321. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  55322. if (totalVertices === void 0) { totalVertices = null; }
  55323. if (this.sourceMesh) {
  55324. this.sourceMesh.setIndices(indices, totalVertices);
  55325. }
  55326. return this.sourceMesh;
  55327. };
  55328. /**
  55329. * Boolean : True if the mesh owns the requested kind of data.
  55330. */
  55331. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  55332. return this._sourceMesh.isVerticesDataPresent(kind);
  55333. };
  55334. /**
  55335. * Returns an array of indices (IndicesArray).
  55336. */
  55337. InstancedMesh.prototype.getIndices = function () {
  55338. return this._sourceMesh.getIndices();
  55339. };
  55340. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  55341. get: function () {
  55342. return this._sourceMesh._positions;
  55343. },
  55344. enumerable: true,
  55345. configurable: true
  55346. });
  55347. /**
  55348. * Sets a new updated BoundingInfo to the mesh.
  55349. * Returns the mesh.
  55350. */
  55351. InstancedMesh.prototype.refreshBoundingInfo = function () {
  55352. var meshBB = this._sourceMesh.getBoundingInfo();
  55353. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  55354. this._updateBoundingInfo();
  55355. return this;
  55356. };
  55357. InstancedMesh.prototype._preActivate = function () {
  55358. if (this._currentLOD) {
  55359. this._currentLOD._preActivate();
  55360. }
  55361. return this;
  55362. };
  55363. InstancedMesh.prototype._activate = function (renderId) {
  55364. if (this._currentLOD) {
  55365. this._currentLOD._registerInstanceForRenderId(this, renderId);
  55366. }
  55367. return this;
  55368. };
  55369. /**
  55370. * Returns the current associated LOD AbstractMesh.
  55371. */
  55372. InstancedMesh.prototype.getLOD = function (camera) {
  55373. if (!camera) {
  55374. return this;
  55375. }
  55376. var boundingInfo = this.getBoundingInfo();
  55377. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  55378. if (this._currentLOD === this.sourceMesh) {
  55379. return this;
  55380. }
  55381. return this._currentLOD;
  55382. };
  55383. InstancedMesh.prototype._syncSubMeshes = function () {
  55384. this.releaseSubMeshes();
  55385. if (this._sourceMesh.subMeshes) {
  55386. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  55387. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  55388. }
  55389. }
  55390. return this;
  55391. };
  55392. InstancedMesh.prototype._generatePointsArray = function () {
  55393. return this._sourceMesh._generatePointsArray();
  55394. };
  55395. /**
  55396. * Creates a new InstancedMesh from the current mesh.
  55397. * - name (string) : the cloned mesh name
  55398. * - newParent (optional Node) : the optional Node to parent the clone to.
  55399. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  55400. *
  55401. * Returns the clone.
  55402. */
  55403. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  55404. var result = this._sourceMesh.createInstance(name);
  55405. // Deep copy
  55406. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  55407. // Bounding info
  55408. this.refreshBoundingInfo();
  55409. // Parent
  55410. if (newParent) {
  55411. result.parent = newParent;
  55412. }
  55413. if (!doNotCloneChildren) {
  55414. // Children
  55415. for (var index = 0; index < this.getScene().meshes.length; index++) {
  55416. var mesh = this.getScene().meshes[index];
  55417. if (mesh.parent === this) {
  55418. mesh.clone(mesh.name, result);
  55419. }
  55420. }
  55421. }
  55422. result.computeWorldMatrix(true);
  55423. return result;
  55424. };
  55425. /**
  55426. * Disposes the InstancedMesh.
  55427. * Returns nothing.
  55428. */
  55429. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  55430. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  55431. // Remove from mesh
  55432. var index = this._sourceMesh.instances.indexOf(this);
  55433. this._sourceMesh.instances.splice(index, 1);
  55434. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  55435. };
  55436. return InstancedMesh;
  55437. }(BABYLON.AbstractMesh));
  55438. BABYLON.InstancedMesh = InstancedMesh;
  55439. })(BABYLON || (BABYLON = {}));
  55440. //# sourceMappingURL=babylon.instancedMesh.js.map
  55441. "use strict";
  55442. var BABYLON;
  55443. (function (BABYLON) {
  55444. var LinesMesh = /** @class */ (function (_super) {
  55445. __extends(LinesMesh, _super);
  55446. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  55447. if (scene === void 0) { scene = null; }
  55448. if (parent === void 0) { parent = null; }
  55449. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  55450. _this.useVertexColor = useVertexColor;
  55451. _this.useVertexAlpha = useVertexAlpha;
  55452. _this.color = new BABYLON.Color3(1, 1, 1);
  55453. _this.alpha = 1;
  55454. if (source) {
  55455. _this.color = source.color.clone();
  55456. _this.alpha = source.alpha;
  55457. _this.useVertexColor = source.useVertexColor;
  55458. _this.useVertexAlpha = source.useVertexAlpha;
  55459. }
  55460. _this._intersectionThreshold = 0.1;
  55461. var defines = [];
  55462. var options = {
  55463. attributes: [BABYLON.VertexBuffer.PositionKind],
  55464. uniforms: ["world", "viewProjection"],
  55465. needAlphaBlending: true,
  55466. defines: defines
  55467. };
  55468. if (useVertexAlpha === false) {
  55469. options.needAlphaBlending = false;
  55470. }
  55471. if (!useVertexColor) {
  55472. options.uniforms.push("color");
  55473. }
  55474. else {
  55475. options.defines.push("#define VERTEXCOLOR");
  55476. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  55477. }
  55478. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  55479. return _this;
  55480. }
  55481. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  55482. /**
  55483. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  55484. * This margin is expressed in world space coordinates, so its value may vary.
  55485. * Default value is 0.1
  55486. * @returns the intersection Threshold value.
  55487. */
  55488. get: function () {
  55489. return this._intersectionThreshold;
  55490. },
  55491. /**
  55492. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  55493. * This margin is expressed in world space coordinates, so its value may vary.
  55494. * @param value the new threshold to apply
  55495. */
  55496. set: function (value) {
  55497. if (this._intersectionThreshold === value) {
  55498. return;
  55499. }
  55500. this._intersectionThreshold = value;
  55501. if (this.geometry) {
  55502. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  55503. }
  55504. },
  55505. enumerable: true,
  55506. configurable: true
  55507. });
  55508. /**
  55509. * Returns the string "LineMesh"
  55510. */
  55511. LinesMesh.prototype.getClassName = function () {
  55512. return "LinesMesh";
  55513. };
  55514. Object.defineProperty(LinesMesh.prototype, "material", {
  55515. get: function () {
  55516. return this._colorShader;
  55517. },
  55518. set: function (value) {
  55519. // Do nothing
  55520. },
  55521. enumerable: true,
  55522. configurable: true
  55523. });
  55524. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  55525. get: function () {
  55526. return false;
  55527. },
  55528. enumerable: true,
  55529. configurable: true
  55530. });
  55531. LinesMesh.prototype.createInstance = function (name) {
  55532. throw new Error("LinesMeshes do not support createInstance.");
  55533. };
  55534. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  55535. if (!this._geometry) {
  55536. return this;
  55537. }
  55538. // VBOs
  55539. this._geometry._bind(this._colorShader.getEffect());
  55540. // Color
  55541. if (!this.useVertexColor) {
  55542. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  55543. }
  55544. return this;
  55545. };
  55546. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  55547. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  55548. return this;
  55549. }
  55550. var engine = this.getScene().getEngine();
  55551. // Draw order
  55552. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  55553. return this;
  55554. };
  55555. LinesMesh.prototype.dispose = function (doNotRecurse) {
  55556. this._colorShader.dispose();
  55557. _super.prototype.dispose.call(this, doNotRecurse);
  55558. };
  55559. /**
  55560. * Returns a new LineMesh object cloned from the current one.
  55561. */
  55562. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  55563. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  55564. };
  55565. return LinesMesh;
  55566. }(BABYLON.Mesh));
  55567. BABYLON.LinesMesh = LinesMesh;
  55568. })(BABYLON || (BABYLON = {}));
  55569. //# sourceMappingURL=babylon.linesMesh.js.map
  55570. "use strict";
  55571. var BABYLON;
  55572. (function (BABYLON) {
  55573. var MeshBuilder = /** @class */ (function () {
  55574. function MeshBuilder() {
  55575. }
  55576. MeshBuilder.updateSideOrientation = function (orientation) {
  55577. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  55578. return BABYLON.Mesh.DOUBLESIDE;
  55579. }
  55580. if (orientation === undefined || orientation === null) {
  55581. return BABYLON.Mesh.FRONTSIDE;
  55582. }
  55583. return orientation;
  55584. };
  55585. /**
  55586. * Creates a box mesh.
  55587. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  55588. * The parameter `size` sets the size (float) of each box side (default 1).
  55589. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  55590. * 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).
  55591. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  55592. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55593. * 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).
  55594. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55595. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55596. */
  55597. MeshBuilder.CreateBox = function (name, options, scene) {
  55598. if (scene === void 0) { scene = null; }
  55599. var box = new BABYLON.Mesh(name, scene);
  55600. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55601. box._originalBuilderSideOrientation = options.sideOrientation;
  55602. var vertexData = BABYLON.VertexData.CreateBox(options);
  55603. vertexData.applyToMesh(box, options.updatable);
  55604. return box;
  55605. };
  55606. /**
  55607. * Creates a sphere mesh.
  55608. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  55609. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  55610. * 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`).
  55611. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  55612. * 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
  55613. * 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).
  55614. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55615. * 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).
  55616. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55617. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55618. */
  55619. MeshBuilder.CreateSphere = function (name, options, scene) {
  55620. var sphere = new BABYLON.Mesh(name, scene);
  55621. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55622. sphere._originalBuilderSideOrientation = options.sideOrientation;
  55623. var vertexData = BABYLON.VertexData.CreateSphere(options);
  55624. vertexData.applyToMesh(sphere, options.updatable);
  55625. return sphere;
  55626. };
  55627. /**
  55628. * Creates a plane polygonal mesh. By default, this is a disc.
  55629. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  55630. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  55631. * 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.
  55632. * 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
  55633. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55634. * 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).
  55635. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55636. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55637. */
  55638. MeshBuilder.CreateDisc = function (name, options, scene) {
  55639. if (scene === void 0) { scene = null; }
  55640. var disc = new BABYLON.Mesh(name, scene);
  55641. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55642. disc._originalBuilderSideOrientation = options.sideOrientation;
  55643. var vertexData = BABYLON.VertexData.CreateDisc(options);
  55644. vertexData.applyToMesh(disc, options.updatable);
  55645. return disc;
  55646. };
  55647. /**
  55648. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  55649. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  55650. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  55651. * 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`).
  55652. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  55653. * 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.
  55654. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55655. * 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).
  55656. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55657. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55658. */
  55659. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  55660. var sphere = new BABYLON.Mesh(name, scene);
  55661. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55662. sphere._originalBuilderSideOrientation = options.sideOrientation;
  55663. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  55664. vertexData.applyToMesh(sphere, options.updatable);
  55665. return sphere;
  55666. };
  55667. ;
  55668. /**
  55669. * Creates a ribbon mesh.
  55670. * 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.
  55671. *
  55672. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  55673. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  55674. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  55675. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  55676. * 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.
  55677. * 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.
  55678. * 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
  55679. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55680. * 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).
  55681. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55682. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55683. * 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.
  55684. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  55685. * 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
  55686. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  55687. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  55688. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55689. */
  55690. MeshBuilder.CreateRibbon = function (name, options, scene) {
  55691. if (scene === void 0) { scene = null; }
  55692. var pathArray = options.pathArray;
  55693. var closeArray = options.closeArray;
  55694. var closePath = options.closePath;
  55695. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55696. var instance = options.instance;
  55697. var updatable = options.updatable;
  55698. if (instance) {
  55699. // positionFunction : ribbon case
  55700. // only pathArray and sideOrientation parameters are taken into account for positions update
  55701. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  55702. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  55703. var positionFunction = function (positions) {
  55704. var minlg = pathArray[0].length;
  55705. var i = 0;
  55706. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  55707. for (var si = 1; si <= ns; si++) {
  55708. for (var p = 0; p < pathArray.length; p++) {
  55709. var path = pathArray[p];
  55710. var l = path.length;
  55711. minlg = (minlg < l) ? minlg : l;
  55712. var j = 0;
  55713. while (j < minlg) {
  55714. positions[i] = path[j].x;
  55715. positions[i + 1] = path[j].y;
  55716. positions[i + 2] = path[j].z;
  55717. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  55718. BABYLON.Tmp.Vector3[0].x = path[j].x;
  55719. }
  55720. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  55721. BABYLON.Tmp.Vector3[1].x = path[j].x;
  55722. }
  55723. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  55724. BABYLON.Tmp.Vector3[0].y = path[j].y;
  55725. }
  55726. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  55727. BABYLON.Tmp.Vector3[1].y = path[j].y;
  55728. }
  55729. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  55730. BABYLON.Tmp.Vector3[0].z = path[j].z;
  55731. }
  55732. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  55733. BABYLON.Tmp.Vector3[1].z = path[j].z;
  55734. }
  55735. j++;
  55736. i += 3;
  55737. }
  55738. if (instance._closePath) {
  55739. positions[i] = path[0].x;
  55740. positions[i + 1] = path[0].y;
  55741. positions[i + 2] = path[0].z;
  55742. i += 3;
  55743. }
  55744. }
  55745. }
  55746. };
  55747. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55748. positionFunction(positions);
  55749. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  55750. instance._boundingInfo.update(instance._worldMatrix);
  55751. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55752. if (options.colors) {
  55753. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55754. for (var c = 0; c < options.colors.length; c++) {
  55755. colors[c * 4] = options.colors[c].r;
  55756. colors[c * 4 + 1] = options.colors[c].g;
  55757. colors[c * 4 + 2] = options.colors[c].b;
  55758. colors[c * 4 + 3] = options.colors[c].a;
  55759. }
  55760. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  55761. }
  55762. if (options.uvs) {
  55763. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55764. for (var i = 0; i < options.uvs.length; i++) {
  55765. uvs[i * 2] = options.uvs[i].x;
  55766. uvs[i * 2 + 1] = options.uvs[i].y;
  55767. }
  55768. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  55769. }
  55770. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  55771. var indices = instance.getIndices();
  55772. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55773. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  55774. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  55775. if (instance._closePath) {
  55776. var indexFirst = 0;
  55777. var indexLast = 0;
  55778. for (var p = 0; p < pathArray.length; p++) {
  55779. indexFirst = instance._idx[p] * 3;
  55780. if (p + 1 < pathArray.length) {
  55781. indexLast = (instance._idx[p + 1] - 1) * 3;
  55782. }
  55783. else {
  55784. indexLast = normals.length - 3;
  55785. }
  55786. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  55787. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  55788. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  55789. normals[indexLast] = normals[indexFirst];
  55790. normals[indexLast + 1] = normals[indexFirst + 1];
  55791. normals[indexLast + 2] = normals[indexFirst + 2];
  55792. }
  55793. }
  55794. if (!(instance.areNormalsFrozen)) {
  55795. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  55796. }
  55797. }
  55798. return instance;
  55799. }
  55800. else {
  55801. var ribbon = new BABYLON.Mesh(name, scene);
  55802. ribbon._originalBuilderSideOrientation = sideOrientation;
  55803. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  55804. if (closePath) {
  55805. ribbon._idx = vertexData._idx;
  55806. }
  55807. ribbon._closePath = closePath;
  55808. ribbon._closeArray = closeArray;
  55809. vertexData.applyToMesh(ribbon, updatable);
  55810. return ribbon;
  55811. }
  55812. };
  55813. /**
  55814. * Creates a cylinder or a cone mesh.
  55815. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  55816. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  55817. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  55818. * 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.
  55819. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  55820. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  55821. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  55822. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  55823. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  55824. * 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).
  55825. * 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
  55826. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  55827. * 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
  55828. * 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.
  55829. * If `enclose` is false, a ring surface is one element.
  55830. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  55831. * 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
  55832. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55833. * 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).
  55834. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55835. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55836. */
  55837. MeshBuilder.CreateCylinder = function (name, options, scene) {
  55838. var cylinder = new BABYLON.Mesh(name, scene);
  55839. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55840. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  55841. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  55842. vertexData.applyToMesh(cylinder, options.updatable);
  55843. return cylinder;
  55844. };
  55845. /**
  55846. * Creates a torus mesh.
  55847. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  55848. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  55849. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  55850. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  55851. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55852. * 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).
  55853. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55854. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55855. */
  55856. MeshBuilder.CreateTorus = function (name, options, scene) {
  55857. var torus = new BABYLON.Mesh(name, scene);
  55858. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55859. torus._originalBuilderSideOrientation = options.sideOrientation;
  55860. var vertexData = BABYLON.VertexData.CreateTorus(options);
  55861. vertexData.applyToMesh(torus, options.updatable);
  55862. return torus;
  55863. };
  55864. /**
  55865. * Creates a torus knot mesh.
  55866. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  55867. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  55868. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  55869. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  55870. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  55871. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55872. * 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).
  55873. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55874. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55875. */
  55876. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  55877. var torusKnot = new BABYLON.Mesh(name, scene);
  55878. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55879. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  55880. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  55881. vertexData.applyToMesh(torusKnot, options.updatable);
  55882. return torusKnot;
  55883. };
  55884. /**
  55885. * Creates a line system mesh.
  55886. * A line system is a pool of many lines gathered in a single mesh.
  55887. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  55888. * 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.
  55889. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  55890. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  55891. * 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
  55892. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  55893. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  55894. * 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
  55895. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  55896. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55897. */
  55898. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  55899. var instance = options.instance;
  55900. var lines = options.lines;
  55901. var colors = options.colors;
  55902. if (instance) {
  55903. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55904. var vertexColor;
  55905. var lineColors;
  55906. if (colors) {
  55907. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55908. }
  55909. var i = 0;
  55910. var c = 0;
  55911. for (var l = 0; l < lines.length; l++) {
  55912. var points = lines[l];
  55913. for (var p = 0; p < points.length; p++) {
  55914. positions[i] = points[p].x;
  55915. positions[i + 1] = points[p].y;
  55916. positions[i + 2] = points[p].z;
  55917. if (colors && vertexColor) {
  55918. lineColors = colors[l];
  55919. vertexColor[c] = lineColors[p].r;
  55920. vertexColor[c + 1] = lineColors[p].g;
  55921. vertexColor[c + 2] = lineColors[p].b;
  55922. vertexColor[c + 3] = lineColors[p].a;
  55923. c += 4;
  55924. }
  55925. i += 3;
  55926. }
  55927. }
  55928. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55929. if (colors && vertexColor) {
  55930. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  55931. }
  55932. return instance;
  55933. }
  55934. // line system creation
  55935. var useVertexColor = (colors) ? true : false;
  55936. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  55937. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  55938. vertexData.applyToMesh(lineSystem, options.updatable);
  55939. return lineSystem;
  55940. };
  55941. /**
  55942. * Creates a line mesh.
  55943. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  55944. * 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.
  55945. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55946. * The parameter `points` is an array successive Vector3.
  55947. * 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
  55948. * The optional parameter `colors` is an array of successive Color4, one per line point.
  55949. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  55950. * When updating an instance, remember that only point positions can change, not the number of points.
  55951. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55952. */
  55953. MeshBuilder.CreateLines = function (name, options, scene) {
  55954. if (scene === void 0) { scene = null; }
  55955. var colors = (options.colors) ? [options.colors] : null;
  55956. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  55957. return lines;
  55958. };
  55959. /**
  55960. * Creates a dashed line mesh.
  55961. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  55962. * 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.
  55963. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55964. * The parameter `points` is an array successive Vector3.
  55965. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  55966. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  55967. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  55968. * 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
  55969. * When updating an instance, remember that only point positions can change, not the number of points.
  55970. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55971. */
  55972. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  55973. if (scene === void 0) { scene = null; }
  55974. var points = options.points;
  55975. var instance = options.instance;
  55976. var gapSize = options.gapSize || 1;
  55977. var dashSize = options.dashSize || 3;
  55978. if (instance) {
  55979. var positionFunction = function (positions) {
  55980. var curvect = BABYLON.Vector3.Zero();
  55981. var nbSeg = positions.length / 6;
  55982. var lg = 0;
  55983. var nb = 0;
  55984. var shft = 0;
  55985. var dashshft = 0;
  55986. var curshft = 0;
  55987. var p = 0;
  55988. var i = 0;
  55989. var j = 0;
  55990. for (i = 0; i < points.length - 1; i++) {
  55991. points[i + 1].subtractToRef(points[i], curvect);
  55992. lg += curvect.length();
  55993. }
  55994. shft = lg / nbSeg;
  55995. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  55996. for (i = 0; i < points.length - 1; i++) {
  55997. points[i + 1].subtractToRef(points[i], curvect);
  55998. nb = Math.floor(curvect.length() / shft);
  55999. curvect.normalize();
  56000. j = 0;
  56001. while (j < nb && p < positions.length) {
  56002. curshft = shft * j;
  56003. positions[p] = points[i].x + curshft * curvect.x;
  56004. positions[p + 1] = points[i].y + curshft * curvect.y;
  56005. positions[p + 2] = points[i].z + curshft * curvect.z;
  56006. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  56007. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  56008. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  56009. p += 6;
  56010. j++;
  56011. }
  56012. }
  56013. while (p < positions.length) {
  56014. positions[p] = points[i].x;
  56015. positions[p + 1] = points[i].y;
  56016. positions[p + 2] = points[i].z;
  56017. p += 3;
  56018. }
  56019. };
  56020. instance.updateMeshPositions(positionFunction, false);
  56021. return instance;
  56022. }
  56023. // dashed lines creation
  56024. var dashedLines = new BABYLON.LinesMesh(name, scene);
  56025. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  56026. vertexData.applyToMesh(dashedLines, options.updatable);
  56027. dashedLines.dashSize = dashSize;
  56028. dashedLines.gapSize = gapSize;
  56029. return dashedLines;
  56030. };
  56031. /**
  56032. * Creates an extruded shape mesh.
  56033. * 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.
  56034. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  56035. *
  56036. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56037. * 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
  56038. * extruded along the Z axis.
  56039. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56040. * 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.
  56041. * The parameter `scale` (float, default 1) is the value to scale the shape.
  56042. * 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
  56043. * 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
  56044. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56045. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56046. * 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).
  56047. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56048. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56049. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56050. */
  56051. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  56052. if (scene === void 0) { scene = null; }
  56053. var path = options.path;
  56054. var shape = options.shape;
  56055. var scale = options.scale || 1;
  56056. var rotation = options.rotation || 0;
  56057. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56058. var updatable = options.updatable;
  56059. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56060. var instance = options.instance || null;
  56061. var invertUV = options.invertUV || false;
  56062. 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);
  56063. };
  56064. /**
  56065. * Creates an custom extruded shape mesh.
  56066. * 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.
  56067. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  56068. *
  56069. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56070. * 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
  56071. * extruded along the Z axis.
  56072. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56073. * 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
  56074. * and the distance of this point from the begining of the path :
  56075. * ```javascript
  56076. * var rotationFunction = function(i, distance) {
  56077. * // do things
  56078. * return rotationValue; }
  56079. * ```
  56080. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  56081. * 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
  56082. * and the distance of this point from the begining of the path :
  56083. * ```javascript
  56084. * var scaleFunction = function(i, distance) {
  56085. * // do things
  56086. * return scaleValue;}
  56087. * ```
  56088. * It must returns a float value that will be the scale value applied to the shape on each path point.
  56089. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  56090. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  56091. * 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
  56092. * 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
  56093. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56094. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56095. * 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).
  56096. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56097. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56098. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56099. */
  56100. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  56101. var path = options.path;
  56102. var shape = options.shape;
  56103. var scaleFunction = options.scaleFunction || (function () { return 1; });
  56104. var rotationFunction = options.rotationFunction || (function () { return 0; });
  56105. var ribbonCloseArray = options.ribbonCloseArray || false;
  56106. var ribbonClosePath = options.ribbonClosePath || false;
  56107. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56108. var updatable = options.updatable;
  56109. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56110. var instance = options.instance;
  56111. var invertUV = options.invertUV || false;
  56112. 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);
  56113. };
  56114. /**
  56115. * Creates lathe mesh.
  56116. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  56117. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  56118. *
  56119. * 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
  56120. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  56121. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  56122. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  56123. * 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.
  56124. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  56125. * 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
  56126. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56127. * 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).
  56128. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56129. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56130. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56131. */
  56132. MeshBuilder.CreateLathe = function (name, options, scene) {
  56133. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  56134. var closed = (options.closed === undefined) ? true : options.closed;
  56135. var shape = options.shape;
  56136. var radius = options.radius || 1;
  56137. var tessellation = options.tessellation || 64;
  56138. var updatable = options.updatable;
  56139. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56140. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  56141. var pi2 = Math.PI * 2;
  56142. var paths = new Array();
  56143. var invertUV = options.invertUV || false;
  56144. var i = 0;
  56145. var p = 0;
  56146. var step = pi2 / tessellation * arc;
  56147. var rotated;
  56148. var path = new Array();
  56149. ;
  56150. for (i = 0; i <= tessellation; i++) {
  56151. var path = [];
  56152. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  56153. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  56154. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  56155. }
  56156. for (p = 0; p < shape.length; p++) {
  56157. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  56158. path.push(rotated);
  56159. }
  56160. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  56161. 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));
  56162. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  56163. }
  56164. paths.push(path);
  56165. }
  56166. // lathe ribbon
  56167. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  56168. return lathe;
  56169. };
  56170. /**
  56171. * Creates a plane mesh.
  56172. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56173. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  56174. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  56175. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  56176. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56177. * 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).
  56178. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56179. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56180. */
  56181. MeshBuilder.CreatePlane = function (name, options, scene) {
  56182. var plane = new BABYLON.Mesh(name, scene);
  56183. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56184. plane._originalBuilderSideOrientation = options.sideOrientation;
  56185. var vertexData = BABYLON.VertexData.CreatePlane(options);
  56186. vertexData.applyToMesh(plane, options.updatable);
  56187. if (options.sourcePlane) {
  56188. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  56189. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  56190. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  56191. plane.rotate(vectorProduct, product);
  56192. }
  56193. return plane;
  56194. };
  56195. /**
  56196. * Creates a ground mesh.
  56197. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56198. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  56199. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  56200. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56201. */
  56202. MeshBuilder.CreateGround = function (name, options, scene) {
  56203. var ground = new BABYLON.GroundMesh(name, scene);
  56204. ground._setReady(false);
  56205. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  56206. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  56207. ground._width = options.width || 1;
  56208. ground._height = options.height || 1;
  56209. ground._maxX = ground._width / 2;
  56210. ground._maxZ = ground._height / 2;
  56211. ground._minX = -ground._maxX;
  56212. ground._minZ = -ground._maxZ;
  56213. var vertexData = BABYLON.VertexData.CreateGround(options);
  56214. vertexData.applyToMesh(ground, options.updatable);
  56215. ground._setReady(true);
  56216. return ground;
  56217. };
  56218. /**
  56219. * Creates a tiled ground mesh.
  56220. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  56221. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  56222. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  56223. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  56224. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  56225. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  56226. * numbers of subdivisions on the ground width and height of each tile.
  56227. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56228. */
  56229. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  56230. var tiledGround = new BABYLON.Mesh(name, scene);
  56231. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  56232. vertexData.applyToMesh(tiledGround, options.updatable);
  56233. return tiledGround;
  56234. };
  56235. /**
  56236. * Creates a ground mesh from a height map.
  56237. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  56238. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  56239. * The parameter `url` sets the URL of the height map image resource.
  56240. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  56241. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  56242. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  56243. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  56244. * 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.
  56245. * 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).
  56246. * This function is passed the newly built mesh :
  56247. * ```javascript
  56248. * function(mesh) { // do things
  56249. * return; }
  56250. * ```
  56251. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56252. */
  56253. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  56254. var width = options.width || 10.0;
  56255. var height = options.height || 10.0;
  56256. var subdivisions = options.subdivisions || 1 | 0;
  56257. var minHeight = options.minHeight || 0.0;
  56258. var maxHeight = options.maxHeight || 1.0;
  56259. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  56260. var updatable = options.updatable;
  56261. var onReady = options.onReady;
  56262. var ground = new BABYLON.GroundMesh(name, scene);
  56263. ground._subdivisionsX = subdivisions;
  56264. ground._subdivisionsY = subdivisions;
  56265. ground._width = width;
  56266. ground._height = height;
  56267. ground._maxX = ground._width / 2.0;
  56268. ground._maxZ = ground._height / 2.0;
  56269. ground._minX = -ground._maxX;
  56270. ground._minZ = -ground._maxZ;
  56271. ground._setReady(false);
  56272. var onload = function (img) {
  56273. // Getting height map data
  56274. var canvas = document.createElement("canvas");
  56275. var context = canvas.getContext("2d");
  56276. if (!context) {
  56277. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  56278. }
  56279. if (scene.isDisposed) {
  56280. return;
  56281. }
  56282. var bufferWidth = img.width;
  56283. var bufferHeight = img.height;
  56284. canvas.width = bufferWidth;
  56285. canvas.height = bufferHeight;
  56286. context.drawImage(img, 0, 0);
  56287. // Create VertexData from map data
  56288. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  56289. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  56290. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  56291. width: width, height: height,
  56292. subdivisions: subdivisions,
  56293. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  56294. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  56295. });
  56296. vertexData.applyToMesh(ground, updatable);
  56297. //execute ready callback, if set
  56298. if (onReady) {
  56299. onReady(ground);
  56300. }
  56301. ground._setReady(true);
  56302. };
  56303. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  56304. return ground;
  56305. };
  56306. /**
  56307. * Creates a polygon mesh.
  56308. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  56309. * 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.
  56310. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56311. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56312. * 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).
  56313. * Remember you can only change the shape positions, not their number when updating a polygon.
  56314. */
  56315. MeshBuilder.CreatePolygon = function (name, options, scene) {
  56316. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56317. var shape = options.shape;
  56318. var holes = options.holes || [];
  56319. var depth = options.depth || 0;
  56320. var contours = [];
  56321. var hole = [];
  56322. for (var i = 0; i < shape.length; i++) {
  56323. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  56324. }
  56325. var epsilon = 0.00000001;
  56326. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  56327. contours.pop();
  56328. }
  56329. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  56330. for (var hNb = 0; hNb < holes.length; hNb++) {
  56331. hole = [];
  56332. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  56333. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  56334. }
  56335. polygonTriangulation.addHole(hole);
  56336. }
  56337. var polygon = polygonTriangulation.build(options.updatable, depth);
  56338. polygon._originalBuilderSideOrientation = options.sideOrientation;
  56339. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  56340. vertexData.applyToMesh(polygon, options.updatable);
  56341. return polygon;
  56342. };
  56343. ;
  56344. /**
  56345. * Creates an extruded polygon mesh, with depth in the Y direction.
  56346. * 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).
  56347. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  56348. */
  56349. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  56350. return MeshBuilder.CreatePolygon(name, options, scene);
  56351. };
  56352. ;
  56353. /**
  56354. * Creates a tube mesh.
  56355. * 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.
  56356. *
  56357. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  56358. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  56359. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  56360. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  56361. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  56362. * 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.
  56363. * It must return a radius value (positive float) :
  56364. * ```javascript
  56365. * var radiusFunction = function(i, distance) {
  56366. * // do things
  56367. * return radius; }
  56368. * ```
  56369. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  56370. * 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
  56371. * 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
  56372. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56373. * 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).
  56374. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56375. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56376. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56377. */
  56378. MeshBuilder.CreateTube = function (name, options, scene) {
  56379. var path = options.path;
  56380. var instance = options.instance;
  56381. var radius = 1.0;
  56382. if (instance) {
  56383. radius = instance.radius;
  56384. }
  56385. if (options.radius !== undefined) {
  56386. radius = options.radius;
  56387. }
  56388. ;
  56389. var tessellation = options.tessellation || 64 | 0;
  56390. var radiusFunction = options.radiusFunction || null;
  56391. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  56392. var invertUV = options.invertUV || false;
  56393. var updatable = options.updatable;
  56394. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56395. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  56396. // tube geometry
  56397. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  56398. var tangents = path3D.getTangents();
  56399. var normals = path3D.getNormals();
  56400. var distances = path3D.getDistances();
  56401. var pi2 = Math.PI * 2;
  56402. var step = pi2 / tessellation * arc;
  56403. var returnRadius = function () { return radius; };
  56404. var radiusFunctionFinal = radiusFunction || returnRadius;
  56405. var circlePath;
  56406. var rad;
  56407. var normal;
  56408. var rotated;
  56409. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  56410. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  56411. for (var i = 0; i < path.length; i++) {
  56412. rad = radiusFunctionFinal(i, distances[i]); // current radius
  56413. circlePath = Array(); // current circle array
  56414. normal = normals[i]; // current normal
  56415. for (var t = 0; t < tessellation; t++) {
  56416. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  56417. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  56418. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  56419. rotated.scaleInPlace(rad).addInPlace(path[i]);
  56420. circlePath[t] = rotated;
  56421. }
  56422. circlePaths[index] = circlePath;
  56423. index++;
  56424. }
  56425. // cap
  56426. var capPath = function (nbPoints, pathIndex) {
  56427. var pointCap = Array();
  56428. for (var i = 0; i < nbPoints; i++) {
  56429. pointCap.push(path[pathIndex]);
  56430. }
  56431. return pointCap;
  56432. };
  56433. switch (cap) {
  56434. case BABYLON.Mesh.NO_CAP:
  56435. break;
  56436. case BABYLON.Mesh.CAP_START:
  56437. circlePaths[0] = capPath(tessellation, 0);
  56438. circlePaths[1] = circlePaths[2].slice(0);
  56439. break;
  56440. case BABYLON.Mesh.CAP_END:
  56441. circlePaths[index] = circlePaths[index - 1].slice(0);
  56442. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  56443. break;
  56444. case BABYLON.Mesh.CAP_ALL:
  56445. circlePaths[0] = capPath(tessellation, 0);
  56446. circlePaths[1] = circlePaths[2].slice(0);
  56447. circlePaths[index] = circlePaths[index - 1].slice(0);
  56448. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  56449. break;
  56450. default:
  56451. break;
  56452. }
  56453. return circlePaths;
  56454. };
  56455. var path3D;
  56456. var pathArray;
  56457. if (instance) {
  56458. var arc = options.arc || instance.arc;
  56459. path3D = (instance.path3D).update(path);
  56460. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  56461. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  56462. instance.path3D = path3D;
  56463. instance.pathArray = pathArray;
  56464. instance.arc = arc;
  56465. instance.radius = radius;
  56466. return instance;
  56467. }
  56468. // tube creation
  56469. path3D = new BABYLON.Path3D(path);
  56470. var newPathArray = new Array();
  56471. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56472. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  56473. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  56474. tube.pathArray = pathArray;
  56475. tube.path3D = path3D;
  56476. tube.tessellation = tessellation;
  56477. tube.cap = cap;
  56478. tube.arc = options.arc;
  56479. tube.radius = radius;
  56480. return tube;
  56481. };
  56482. /**
  56483. * Creates a polyhedron mesh.
  56484. *
  56485. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  56486. * 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
  56487. * to choose the wanted type.
  56488. * The parameter `size` (positive float, default 1) sets the polygon size.
  56489. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  56490. * 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`.
  56491. * 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
  56492. * 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)`).
  56493. * 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
  56494. * 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.
  56495. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56496. * 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).
  56497. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56498. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56499. */
  56500. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  56501. var polyhedron = new BABYLON.Mesh(name, scene);
  56502. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56503. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  56504. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  56505. vertexData.applyToMesh(polyhedron, options.updatable);
  56506. return polyhedron;
  56507. };
  56508. /**
  56509. * Creates a decal mesh.
  56510. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  56511. * 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.
  56512. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  56513. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  56514. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  56515. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  56516. */
  56517. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  56518. var indices = sourceMesh.getIndices();
  56519. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56520. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56521. var position = options.position || BABYLON.Vector3.Zero();
  56522. var normal = options.normal || BABYLON.Vector3.Up();
  56523. var size = options.size || BABYLON.Vector3.One();
  56524. var angle = options.angle || 0;
  56525. // Getting correct rotation
  56526. if (!normal) {
  56527. var target = new BABYLON.Vector3(0, 0, 1);
  56528. var camera = sourceMesh.getScene().activeCamera;
  56529. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  56530. normal = camera.globalPosition.subtract(cameraWorldTarget);
  56531. }
  56532. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  56533. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  56534. var pitch = Math.atan2(normal.y, len);
  56535. // Matrix
  56536. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  56537. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  56538. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  56539. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  56540. var vertexData = new BABYLON.VertexData();
  56541. vertexData.indices = [];
  56542. vertexData.positions = [];
  56543. vertexData.normals = [];
  56544. vertexData.uvs = [];
  56545. var currentVertexDataIndex = 0;
  56546. var extractDecalVector3 = function (indexId) {
  56547. var result = new BABYLON.PositionNormalVertex();
  56548. if (!indices || !positions || !normals) {
  56549. return result;
  56550. }
  56551. var vertexId = indices[indexId];
  56552. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  56553. // Send vector to decal local world
  56554. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  56555. // Get normal
  56556. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  56557. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  56558. return result;
  56559. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  56560. var clip = function (vertices, axis) {
  56561. if (vertices.length === 0) {
  56562. return vertices;
  56563. }
  56564. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  56565. var clipVertices = function (v0, v1) {
  56566. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  56567. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  56568. };
  56569. var result = new Array();
  56570. for (var index = 0; index < vertices.length; index += 3) {
  56571. var v1Out;
  56572. var v2Out;
  56573. var v3Out;
  56574. var total = 0;
  56575. var nV1 = null;
  56576. var nV2 = null;
  56577. var nV3 = null;
  56578. var nV4 = null;
  56579. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  56580. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  56581. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  56582. v1Out = d1 > 0;
  56583. v2Out = d2 > 0;
  56584. v3Out = d3 > 0;
  56585. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  56586. switch (total) {
  56587. case 0:
  56588. result.push(vertices[index]);
  56589. result.push(vertices[index + 1]);
  56590. result.push(vertices[index + 2]);
  56591. break;
  56592. case 1:
  56593. if (v1Out) {
  56594. nV1 = vertices[index + 1];
  56595. nV2 = vertices[index + 2];
  56596. nV3 = clipVertices(vertices[index], nV1);
  56597. nV4 = clipVertices(vertices[index], nV2);
  56598. }
  56599. if (v2Out) {
  56600. nV1 = vertices[index];
  56601. nV2 = vertices[index + 2];
  56602. nV3 = clipVertices(vertices[index + 1], nV1);
  56603. nV4 = clipVertices(vertices[index + 1], nV2);
  56604. result.push(nV3);
  56605. result.push(nV2.clone());
  56606. result.push(nV1.clone());
  56607. result.push(nV2.clone());
  56608. result.push(nV3.clone());
  56609. result.push(nV4);
  56610. break;
  56611. }
  56612. if (v3Out) {
  56613. nV1 = vertices[index];
  56614. nV2 = vertices[index + 1];
  56615. nV3 = clipVertices(vertices[index + 2], nV1);
  56616. nV4 = clipVertices(vertices[index + 2], nV2);
  56617. }
  56618. if (nV1 && nV2 && nV3 && nV4) {
  56619. result.push(nV1.clone());
  56620. result.push(nV2.clone());
  56621. result.push(nV3);
  56622. result.push(nV4);
  56623. result.push(nV3.clone());
  56624. result.push(nV2.clone());
  56625. }
  56626. break;
  56627. case 2:
  56628. if (!v1Out) {
  56629. nV1 = vertices[index].clone();
  56630. nV2 = clipVertices(nV1, vertices[index + 1]);
  56631. nV3 = clipVertices(nV1, vertices[index + 2]);
  56632. result.push(nV1);
  56633. result.push(nV2);
  56634. result.push(nV3);
  56635. }
  56636. if (!v2Out) {
  56637. nV1 = vertices[index + 1].clone();
  56638. nV2 = clipVertices(nV1, vertices[index + 2]);
  56639. nV3 = clipVertices(nV1, vertices[index]);
  56640. result.push(nV1);
  56641. result.push(nV2);
  56642. result.push(nV3);
  56643. }
  56644. if (!v3Out) {
  56645. nV1 = vertices[index + 2].clone();
  56646. nV2 = clipVertices(nV1, vertices[index]);
  56647. nV3 = clipVertices(nV1, vertices[index + 1]);
  56648. result.push(nV1);
  56649. result.push(nV2);
  56650. result.push(nV3);
  56651. }
  56652. break;
  56653. case 3:
  56654. break;
  56655. }
  56656. }
  56657. return result;
  56658. };
  56659. for (var index = 0; index < indices.length; index += 3) {
  56660. var faceVertices = new Array();
  56661. faceVertices.push(extractDecalVector3(index));
  56662. faceVertices.push(extractDecalVector3(index + 1));
  56663. faceVertices.push(extractDecalVector3(index + 2));
  56664. // Clip
  56665. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  56666. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  56667. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  56668. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  56669. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  56670. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  56671. if (faceVertices.length === 0) {
  56672. continue;
  56673. }
  56674. // Add UVs and get back to world
  56675. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  56676. var vertex = faceVertices[vIndex];
  56677. //TODO check for Int32Array | Uint32Array | Uint16Array
  56678. vertexData.indices.push(currentVertexDataIndex);
  56679. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  56680. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  56681. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  56682. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  56683. currentVertexDataIndex++;
  56684. }
  56685. }
  56686. // Return mesh
  56687. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  56688. vertexData.applyToMesh(decal);
  56689. decal.position = position.clone();
  56690. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  56691. return decal;
  56692. };
  56693. // Privates
  56694. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  56695. // extrusion geometry
  56696. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  56697. var tangents = path3D.getTangents();
  56698. var normals = path3D.getNormals();
  56699. var binormals = path3D.getBinormals();
  56700. var distances = path3D.getDistances();
  56701. var angle = 0;
  56702. var returnScale = function () { return scale !== null ? scale : 1; };
  56703. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  56704. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  56705. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  56706. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  56707. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  56708. for (var i = 0; i < curve.length; i++) {
  56709. var shapePath = new Array();
  56710. var angleStep = rotate(i, distances[i]);
  56711. var scaleRatio = scl(i, distances[i]);
  56712. for (var p = 0; p < shape.length; p++) {
  56713. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  56714. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  56715. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  56716. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  56717. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  56718. shapePath[p] = rotated;
  56719. }
  56720. shapePaths[index] = shapePath;
  56721. angle += angleStep;
  56722. index++;
  56723. }
  56724. // cap
  56725. var capPath = function (shapePath) {
  56726. var pointCap = Array();
  56727. var barycenter = BABYLON.Vector3.Zero();
  56728. var i;
  56729. for (i = 0; i < shapePath.length; i++) {
  56730. barycenter.addInPlace(shapePath[i]);
  56731. }
  56732. barycenter.scaleInPlace(1.0 / shapePath.length);
  56733. for (i = 0; i < shapePath.length; i++) {
  56734. pointCap.push(barycenter);
  56735. }
  56736. return pointCap;
  56737. };
  56738. switch (cap) {
  56739. case BABYLON.Mesh.NO_CAP:
  56740. break;
  56741. case BABYLON.Mesh.CAP_START:
  56742. shapePaths[0] = capPath(shapePaths[2]);
  56743. shapePaths[1] = shapePaths[2];
  56744. break;
  56745. case BABYLON.Mesh.CAP_END:
  56746. shapePaths[index] = shapePaths[index - 1];
  56747. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56748. break;
  56749. case BABYLON.Mesh.CAP_ALL:
  56750. shapePaths[0] = capPath(shapePaths[2]);
  56751. shapePaths[1] = shapePaths[2];
  56752. shapePaths[index] = shapePaths[index - 1];
  56753. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56754. break;
  56755. default:
  56756. break;
  56757. }
  56758. return shapePaths;
  56759. };
  56760. var path3D;
  56761. var pathArray;
  56762. if (instance) {
  56763. path3D = (instance.path3D).update(curve);
  56764. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  56765. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  56766. return instance;
  56767. }
  56768. // extruded shape creation
  56769. path3D = new BABYLON.Path3D(curve);
  56770. var newShapePaths = new Array();
  56771. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56772. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  56773. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  56774. extrudedGeneric.pathArray = pathArray;
  56775. extrudedGeneric.path3D = path3D;
  56776. extrudedGeneric.cap = cap;
  56777. return extrudedGeneric;
  56778. };
  56779. return MeshBuilder;
  56780. }());
  56781. BABYLON.MeshBuilder = MeshBuilder;
  56782. })(BABYLON || (BABYLON = {}));
  56783. //# sourceMappingURL=babylon.meshBuilder.js.map
  56784. "use strict";
  56785. var BABYLON;
  56786. (function (BABYLON) {
  56787. /**
  56788. * Draco compression (https://google.github.io/draco/)
  56789. */
  56790. var DracoCompression = /** @class */ (function () {
  56791. /**
  56792. * Constructor
  56793. * @param numWorkers The number of workers for async operations
  56794. */
  56795. function DracoCompression(numWorkers) {
  56796. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  56797. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  56798. if (!workerBlobUrl || !Worker) {
  56799. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  56800. return;
  56801. }
  56802. var workers = new Array(numWorkers);
  56803. for (var i = 0; i < workers.length; i++) {
  56804. var worker = new Worker(workerBlobUrl);
  56805. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  56806. workers[i] = worker;
  56807. }
  56808. this._workerPool = new BABYLON.WorkerPool(workers);
  56809. }
  56810. /**
  56811. * Stop all async operations and release resources.
  56812. */
  56813. DracoCompression.prototype.dispose = function () {
  56814. this._workerPool.dispose();
  56815. delete this._workerPool;
  56816. };
  56817. /**
  56818. * Decode Draco compressed mesh data to vertex data.
  56819. * @param data The array buffer view for the Draco compression data
  56820. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  56821. * @returns A promise that resolves with the decoded vertex data
  56822. */
  56823. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  56824. var _this = this;
  56825. return new Promise(function (resolve, reject) {
  56826. _this._workerPool.push(function (worker, onComplete) {
  56827. var vertexData = new BABYLON.VertexData();
  56828. var onError = function (error) {
  56829. worker.removeEventListener("error", onError);
  56830. worker.removeEventListener("message", onMessage);
  56831. reject(error);
  56832. onComplete();
  56833. };
  56834. var onMessage = function (message) {
  56835. if (message.data === "done") {
  56836. worker.removeEventListener("error", onError);
  56837. worker.removeEventListener("message", onMessage);
  56838. resolve(vertexData);
  56839. onComplete();
  56840. }
  56841. else if (message.data.id === "indices") {
  56842. vertexData.indices = message.data.value;
  56843. }
  56844. else {
  56845. vertexData.set(message.data.value, message.data.id);
  56846. }
  56847. };
  56848. worker.addEventListener("error", onError);
  56849. worker.addEventListener("message", onMessage);
  56850. var dataCopy = new Uint8Array(data.byteLength);
  56851. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  56852. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  56853. });
  56854. });
  56855. };
  56856. /**
  56857. * The worker function that gets converted to a blob url to pass into a worker.
  56858. */
  56859. DracoCompression._Worker = function () {
  56860. // self is actually a DedicatedWorkerGlobalScope
  56861. var _self = self;
  56862. var decodeMesh = function (data, attributes) {
  56863. var dracoModule = new DracoDecoderModule();
  56864. var buffer = new dracoModule.DecoderBuffer();
  56865. buffer.Init(data, data.byteLength);
  56866. var decoder = new dracoModule.Decoder();
  56867. var geometry;
  56868. var status;
  56869. try {
  56870. var type = decoder.GetEncodedGeometryType(buffer);
  56871. switch (type) {
  56872. case dracoModule.TRIANGULAR_MESH:
  56873. geometry = new dracoModule.Mesh();
  56874. status = decoder.DecodeBufferToMesh(buffer, geometry);
  56875. break;
  56876. case dracoModule.POINT_CLOUD:
  56877. geometry = new dracoModule.PointCloud();
  56878. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  56879. break;
  56880. default:
  56881. throw new Error("Invalid geometry type " + type);
  56882. }
  56883. if (!status.ok() || !geometry.ptr) {
  56884. throw new Error(status.error_msg());
  56885. }
  56886. var numPoints = geometry.num_points();
  56887. if (type === dracoModule.TRIANGULAR_MESH) {
  56888. var numFaces = geometry.num_faces();
  56889. var faceIndices = new dracoModule.DracoInt32Array();
  56890. try {
  56891. var indices = new Uint32Array(numFaces * 3);
  56892. for (var i = 0; i < numFaces; i++) {
  56893. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  56894. var offset = i * 3;
  56895. indices[offset + 0] = faceIndices.GetValue(0);
  56896. indices[offset + 1] = faceIndices.GetValue(1);
  56897. indices[offset + 2] = faceIndices.GetValue(2);
  56898. }
  56899. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  56900. }
  56901. finally {
  56902. dracoModule.destroy(faceIndices);
  56903. }
  56904. }
  56905. for (var kind in attributes) {
  56906. var uniqueId = attributes[kind];
  56907. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  56908. var dracoData = new dracoModule.DracoFloat32Array();
  56909. try {
  56910. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  56911. var babylonData = new Float32Array(numPoints * attribute.num_components());
  56912. for (var i = 0; i < babylonData.length; i++) {
  56913. babylonData[i] = dracoData.GetValue(i);
  56914. }
  56915. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  56916. }
  56917. finally {
  56918. dracoModule.destroy(dracoData);
  56919. }
  56920. }
  56921. }
  56922. finally {
  56923. if (geometry) {
  56924. dracoModule.destroy(geometry);
  56925. }
  56926. dracoModule.destroy(decoder);
  56927. dracoModule.destroy(buffer);
  56928. }
  56929. _self.postMessage("done");
  56930. };
  56931. _self.onmessage = function (event) {
  56932. switch (event.data.id) {
  56933. case "initDecoder": {
  56934. importScripts(event.data.url);
  56935. break;
  56936. }
  56937. case "decodeMesh": {
  56938. decodeMesh(event.data.data, event.data.attributes);
  56939. break;
  56940. }
  56941. }
  56942. };
  56943. };
  56944. DracoCompression._GetDefaultDecoderUrl = function () {
  56945. if (!BABYLON.Tools.IsWindowObjectExist()) {
  56946. return null;
  56947. }
  56948. for (var i = 0; i < document.scripts.length; i++) {
  56949. if (document.scripts[i].type === "text/x-draco-decoder") {
  56950. return document.scripts[i].src;
  56951. }
  56952. }
  56953. return null;
  56954. };
  56955. /**
  56956. * Gets the url to the draco decoder if available.
  56957. */
  56958. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  56959. return DracoCompression;
  56960. }());
  56961. BABYLON.DracoCompression = DracoCompression;
  56962. })(BABYLON || (BABYLON = {}));
  56963. //# sourceMappingURL=babylon.dracoCompression.js.map
  56964. "use strict";
  56965. var BABYLON;
  56966. (function (BABYLON) {
  56967. var AudioEngine = /** @class */ (function () {
  56968. function AudioEngine() {
  56969. this._audioContext = null;
  56970. this._audioContextInitialized = false;
  56971. this.canUseWebAudio = false;
  56972. this.WarnedWebAudioUnsupported = false;
  56973. this.unlocked = false;
  56974. this.isMP3supported = false;
  56975. this.isOGGsupported = false;
  56976. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  56977. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  56978. this.canUseWebAudio = true;
  56979. }
  56980. var audioElem = document.createElement('audio');
  56981. try {
  56982. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  56983. this.isMP3supported = true;
  56984. }
  56985. }
  56986. catch (e) {
  56987. // protect error during capability check.
  56988. }
  56989. try {
  56990. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  56991. this.isOGGsupported = true;
  56992. }
  56993. }
  56994. catch (e) {
  56995. // protect error during capability check.
  56996. }
  56997. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  56998. this._unlockiOSaudio();
  56999. }
  57000. else {
  57001. this.unlocked = true;
  57002. }
  57003. }
  57004. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  57005. get: function () {
  57006. if (!this._audioContextInitialized) {
  57007. this._initializeAudioContext();
  57008. }
  57009. return this._audioContext;
  57010. },
  57011. enumerable: true,
  57012. configurable: true
  57013. });
  57014. AudioEngine.prototype._unlockiOSaudio = function () {
  57015. var _this = this;
  57016. var unlockaudio = function () {
  57017. if (!_this.audioContext) {
  57018. return;
  57019. }
  57020. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  57021. var source = _this.audioContext.createBufferSource();
  57022. source.buffer = buffer;
  57023. source.connect(_this.audioContext.destination);
  57024. source.start(0);
  57025. setTimeout(function () {
  57026. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  57027. _this.unlocked = true;
  57028. window.removeEventListener('touchend', unlockaudio, false);
  57029. if (_this.onAudioUnlocked) {
  57030. _this.onAudioUnlocked();
  57031. }
  57032. }
  57033. }, 0);
  57034. };
  57035. window.addEventListener('touchend', unlockaudio, false);
  57036. };
  57037. AudioEngine.prototype._initializeAudioContext = function () {
  57038. try {
  57039. if (this.canUseWebAudio) {
  57040. this._audioContext = new AudioContext();
  57041. // create a global volume gain node
  57042. this.masterGain = this._audioContext.createGain();
  57043. this.masterGain.gain.value = 1;
  57044. this.masterGain.connect(this._audioContext.destination);
  57045. this._audioContextInitialized = true;
  57046. }
  57047. }
  57048. catch (e) {
  57049. this.canUseWebAudio = false;
  57050. BABYLON.Tools.Error("Web Audio: " + e.message);
  57051. }
  57052. };
  57053. AudioEngine.prototype.dispose = function () {
  57054. if (this.canUseWebAudio && this._audioContextInitialized) {
  57055. if (this._connectedAnalyser && this._audioContext) {
  57056. this._connectedAnalyser.stopDebugCanvas();
  57057. this._connectedAnalyser.dispose();
  57058. this.masterGain.disconnect();
  57059. this.masterGain.connect(this._audioContext.destination);
  57060. this._connectedAnalyser = null;
  57061. }
  57062. this.masterGain.gain.value = 1;
  57063. }
  57064. this.WarnedWebAudioUnsupported = false;
  57065. };
  57066. AudioEngine.prototype.getGlobalVolume = function () {
  57067. if (this.canUseWebAudio && this._audioContextInitialized) {
  57068. return this.masterGain.gain.value;
  57069. }
  57070. else {
  57071. return -1;
  57072. }
  57073. };
  57074. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  57075. if (this.canUseWebAudio && this._audioContextInitialized) {
  57076. this.masterGain.gain.value = newVolume;
  57077. }
  57078. };
  57079. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  57080. if (this._connectedAnalyser) {
  57081. this._connectedAnalyser.stopDebugCanvas();
  57082. }
  57083. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  57084. this._connectedAnalyser = analyser;
  57085. this.masterGain.disconnect();
  57086. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  57087. }
  57088. };
  57089. return AudioEngine;
  57090. }());
  57091. BABYLON.AudioEngine = AudioEngine;
  57092. })(BABYLON || (BABYLON = {}));
  57093. //# sourceMappingURL=babylon.audioEngine.js.map
  57094. "use strict";
  57095. var BABYLON;
  57096. (function (BABYLON) {
  57097. var Sound = /** @class */ (function () {
  57098. /**
  57099. * Create a sound and attach it to a scene
  57100. * @param name Name of your sound
  57101. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  57102. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  57103. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  57104. */
  57105. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  57106. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  57107. var _this = this;
  57108. this.autoplay = false;
  57109. this.loop = false;
  57110. this.useCustomAttenuation = false;
  57111. this.spatialSound = false;
  57112. this.refDistance = 1;
  57113. this.rolloffFactor = 1;
  57114. this.maxDistance = 100;
  57115. this.distanceModel = "linear";
  57116. this._panningModel = "equalpower";
  57117. this._playbackRate = 1;
  57118. this._streaming = false;
  57119. this._startTime = 0;
  57120. this._startOffset = 0;
  57121. this._position = BABYLON.Vector3.Zero();
  57122. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  57123. this._volume = 1;
  57124. this._isReadyToPlay = false;
  57125. this.isPlaying = false;
  57126. this.isPaused = false;
  57127. this._isDirectional = false;
  57128. // Used if you'd like to create a directional sound.
  57129. // If not set, the sound will be omnidirectional
  57130. this._coneInnerAngle = 360;
  57131. this._coneOuterAngle = 360;
  57132. this._coneOuterGain = 0;
  57133. this._isOutputConnected = false;
  57134. this._urlType = "Unknown";
  57135. this.name = name;
  57136. this._scene = scene;
  57137. this._readyToPlayCallback = readyToPlayCallback;
  57138. // Default custom attenuation function is a linear attenuation
  57139. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  57140. if (currentDistance < maxDistance) {
  57141. return currentVolume * (1 - currentDistance / maxDistance);
  57142. }
  57143. else {
  57144. return 0;
  57145. }
  57146. };
  57147. if (options) {
  57148. this.autoplay = options.autoplay || false;
  57149. this.loop = options.loop || false;
  57150. // if volume === 0, we need another way to check this option
  57151. if (options.volume !== undefined) {
  57152. this._volume = options.volume;
  57153. }
  57154. this.spatialSound = options.spatialSound || false;
  57155. this.maxDistance = options.maxDistance || 100;
  57156. this.useCustomAttenuation = options.useCustomAttenuation || false;
  57157. this.rolloffFactor = options.rolloffFactor || 1;
  57158. this.refDistance = options.refDistance || 1;
  57159. this.distanceModel = options.distanceModel || "linear";
  57160. this._playbackRate = options.playbackRate || 1;
  57161. this._streaming = options.streaming || false;
  57162. }
  57163. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57164. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  57165. this._soundGain.gain.value = this._volume;
  57166. this._inputAudioNode = this._soundGain;
  57167. this._ouputAudioNode = this._soundGain;
  57168. if (this.spatialSound) {
  57169. this._createSpatialParameters();
  57170. }
  57171. this._scene.mainSoundTrack.AddSound(this);
  57172. var validParameter = true;
  57173. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  57174. if (urlOrArrayBuffer) {
  57175. try {
  57176. if (typeof (urlOrArrayBuffer) === "string")
  57177. this._urlType = "String";
  57178. if (Array.isArray(urlOrArrayBuffer))
  57179. this._urlType = "Array";
  57180. if (urlOrArrayBuffer instanceof ArrayBuffer)
  57181. this._urlType = "ArrayBuffer";
  57182. var urls = [];
  57183. var codecSupportedFound = false;
  57184. switch (this._urlType) {
  57185. case "ArrayBuffer":
  57186. if (urlOrArrayBuffer.byteLength > 0) {
  57187. codecSupportedFound = true;
  57188. this._soundLoaded(urlOrArrayBuffer);
  57189. }
  57190. break;
  57191. case "String":
  57192. urls.push(urlOrArrayBuffer);
  57193. case "Array":
  57194. if (urls.length === 0)
  57195. urls = urlOrArrayBuffer;
  57196. // If we found a supported format, we load it immediately and stop the loop
  57197. for (var i = 0; i < urls.length; i++) {
  57198. var url = urls[i];
  57199. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  57200. codecSupportedFound = true;
  57201. }
  57202. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  57203. codecSupportedFound = true;
  57204. }
  57205. if (url.indexOf(".wav", url.length - 4) !== -1) {
  57206. codecSupportedFound = true;
  57207. }
  57208. if (url.indexOf("blob:") !== -1) {
  57209. codecSupportedFound = true;
  57210. }
  57211. if (codecSupportedFound) {
  57212. // Loading sound using XHR2
  57213. if (!this._streaming) {
  57214. this._scene._loadFile(url, function (data) {
  57215. _this._soundLoaded(data);
  57216. }, undefined, true, true, function (exception) {
  57217. if (exception) {
  57218. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  57219. }
  57220. BABYLON.Tools.Error("Sound creation aborted.");
  57221. _this._scene.mainSoundTrack.RemoveSound(_this);
  57222. });
  57223. }
  57224. else {
  57225. this._htmlAudioElement = new Audio(url);
  57226. this._htmlAudioElement.controls = false;
  57227. this._htmlAudioElement.loop = this.loop;
  57228. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  57229. this._htmlAudioElement.preload = "auto";
  57230. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  57231. _this._isReadyToPlay = true;
  57232. if (_this.autoplay) {
  57233. _this.play();
  57234. }
  57235. if (_this._readyToPlayCallback) {
  57236. _this._readyToPlayCallback();
  57237. }
  57238. });
  57239. document.body.appendChild(this._htmlAudioElement);
  57240. }
  57241. break;
  57242. }
  57243. }
  57244. break;
  57245. default:
  57246. validParameter = false;
  57247. break;
  57248. }
  57249. if (!validParameter) {
  57250. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  57251. }
  57252. else {
  57253. if (!codecSupportedFound) {
  57254. this._isReadyToPlay = true;
  57255. // Simulating a ready to play event to avoid breaking code path
  57256. if (this._readyToPlayCallback) {
  57257. window.setTimeout(function () {
  57258. if (_this._readyToPlayCallback) {
  57259. _this._readyToPlayCallback();
  57260. }
  57261. }, 1000);
  57262. }
  57263. }
  57264. }
  57265. }
  57266. catch (ex) {
  57267. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  57268. this._scene.mainSoundTrack.RemoveSound(this);
  57269. }
  57270. }
  57271. }
  57272. else {
  57273. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  57274. this._scene.mainSoundTrack.AddSound(this);
  57275. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  57276. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  57277. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  57278. }
  57279. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  57280. if (this._readyToPlayCallback) {
  57281. window.setTimeout(function () {
  57282. if (_this._readyToPlayCallback) {
  57283. _this._readyToPlayCallback();
  57284. }
  57285. }, 1000);
  57286. }
  57287. }
  57288. }
  57289. Sound.prototype.dispose = function () {
  57290. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57291. if (this.isPlaying) {
  57292. this.stop();
  57293. }
  57294. this._isReadyToPlay = false;
  57295. if (this.soundTrackId === -1) {
  57296. this._scene.mainSoundTrack.RemoveSound(this);
  57297. }
  57298. else {
  57299. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  57300. }
  57301. if (this._soundGain) {
  57302. this._soundGain.disconnect();
  57303. this._soundGain = null;
  57304. }
  57305. if (this._soundPanner) {
  57306. this._soundPanner.disconnect();
  57307. this._soundPanner = null;
  57308. }
  57309. if (this._soundSource) {
  57310. this._soundSource.disconnect();
  57311. this._soundSource = null;
  57312. }
  57313. this._audioBuffer = null;
  57314. if (this._htmlAudioElement) {
  57315. this._htmlAudioElement.pause();
  57316. this._htmlAudioElement.src = "";
  57317. document.body.removeChild(this._htmlAudioElement);
  57318. }
  57319. if (this._connectedMesh && this._registerFunc) {
  57320. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57321. this._connectedMesh = null;
  57322. }
  57323. }
  57324. };
  57325. Sound.prototype.isReady = function () {
  57326. return this._isReadyToPlay;
  57327. };
  57328. Sound.prototype._soundLoaded = function (audioData) {
  57329. var _this = this;
  57330. if (!BABYLON.Engine.audioEngine.audioContext) {
  57331. return;
  57332. }
  57333. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  57334. _this._audioBuffer = buffer;
  57335. _this._isReadyToPlay = true;
  57336. if (_this.autoplay) {
  57337. _this.play();
  57338. }
  57339. if (_this._readyToPlayCallback) {
  57340. _this._readyToPlayCallback();
  57341. }
  57342. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  57343. };
  57344. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  57345. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57346. this._audioBuffer = audioBuffer;
  57347. this._isReadyToPlay = true;
  57348. }
  57349. };
  57350. Sound.prototype.updateOptions = function (options) {
  57351. if (options) {
  57352. this.loop = options.loop || this.loop;
  57353. this.maxDistance = options.maxDistance || this.maxDistance;
  57354. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  57355. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  57356. this.refDistance = options.refDistance || this.refDistance;
  57357. this.distanceModel = options.distanceModel || this.distanceModel;
  57358. this._playbackRate = options.playbackRate || this._playbackRate;
  57359. this._updateSpatialParameters();
  57360. if (this.isPlaying) {
  57361. if (this._streaming) {
  57362. this._htmlAudioElement.playbackRate = this._playbackRate;
  57363. }
  57364. else {
  57365. if (this._soundSource) {
  57366. this._soundSource.playbackRate.value = this._playbackRate;
  57367. }
  57368. }
  57369. }
  57370. }
  57371. };
  57372. Sound.prototype._createSpatialParameters = function () {
  57373. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57374. if (this._scene.headphone) {
  57375. this._panningModel = "HRTF";
  57376. }
  57377. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  57378. this._updateSpatialParameters();
  57379. this._soundPanner.connect(this._ouputAudioNode);
  57380. this._inputAudioNode = this._soundPanner;
  57381. }
  57382. };
  57383. Sound.prototype._updateSpatialParameters = function () {
  57384. if (this.spatialSound && this._soundPanner) {
  57385. if (this.useCustomAttenuation) {
  57386. // Tricks to disable in a way embedded Web Audio attenuation
  57387. this._soundPanner.distanceModel = "linear";
  57388. this._soundPanner.maxDistance = Number.MAX_VALUE;
  57389. this._soundPanner.refDistance = 1;
  57390. this._soundPanner.rolloffFactor = 1;
  57391. this._soundPanner.panningModel = this._panningModel;
  57392. }
  57393. else {
  57394. this._soundPanner.distanceModel = this.distanceModel;
  57395. this._soundPanner.maxDistance = this.maxDistance;
  57396. this._soundPanner.refDistance = this.refDistance;
  57397. this._soundPanner.rolloffFactor = this.rolloffFactor;
  57398. this._soundPanner.panningModel = this._panningModel;
  57399. }
  57400. }
  57401. };
  57402. Sound.prototype.switchPanningModelToHRTF = function () {
  57403. this._panningModel = "HRTF";
  57404. this._switchPanningModel();
  57405. };
  57406. Sound.prototype.switchPanningModelToEqualPower = function () {
  57407. this._panningModel = "equalpower";
  57408. this._switchPanningModel();
  57409. };
  57410. Sound.prototype._switchPanningModel = function () {
  57411. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  57412. this._soundPanner.panningModel = this._panningModel;
  57413. }
  57414. };
  57415. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  57416. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57417. if (this._isOutputConnected) {
  57418. this._ouputAudioNode.disconnect();
  57419. }
  57420. this._ouputAudioNode.connect(soundTrackAudioNode);
  57421. this._isOutputConnected = true;
  57422. }
  57423. };
  57424. /**
  57425. * Transform this sound into a directional source
  57426. * @param coneInnerAngle Size of the inner cone in degree
  57427. * @param coneOuterAngle Size of the outer cone in degree
  57428. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  57429. */
  57430. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  57431. if (coneOuterAngle < coneInnerAngle) {
  57432. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  57433. return;
  57434. }
  57435. this._coneInnerAngle = coneInnerAngle;
  57436. this._coneOuterAngle = coneOuterAngle;
  57437. this._coneOuterGain = coneOuterGain;
  57438. this._isDirectional = true;
  57439. if (this.isPlaying && this.loop) {
  57440. this.stop();
  57441. this.play();
  57442. }
  57443. };
  57444. Sound.prototype.setPosition = function (newPosition) {
  57445. this._position = newPosition;
  57446. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  57447. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  57448. }
  57449. };
  57450. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  57451. this._localDirection = newLocalDirection;
  57452. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  57453. this._updateDirection();
  57454. }
  57455. };
  57456. Sound.prototype._updateDirection = function () {
  57457. if (!this._connectedMesh || !this._soundPanner) {
  57458. return;
  57459. }
  57460. var mat = this._connectedMesh.getWorldMatrix();
  57461. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  57462. direction.normalize();
  57463. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  57464. };
  57465. Sound.prototype.updateDistanceFromListener = function () {
  57466. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  57467. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  57468. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  57469. }
  57470. };
  57471. Sound.prototype.setAttenuationFunction = function (callback) {
  57472. this._customAttenuationFunction = callback;
  57473. };
  57474. /**
  57475. * Play the sound
  57476. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  57477. * @param offset (optional) Start the sound setting it at a specific time
  57478. */
  57479. Sound.prototype.play = function (time, offset) {
  57480. var _this = this;
  57481. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  57482. try {
  57483. if (this._startOffset < 0) {
  57484. time = -this._startOffset;
  57485. this._startOffset = 0;
  57486. }
  57487. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  57488. if (!this._soundSource || !this._streamingSource) {
  57489. if (this.spatialSound && this._soundPanner) {
  57490. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  57491. if (this._isDirectional) {
  57492. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  57493. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  57494. this._soundPanner.coneOuterGain = this._coneOuterGain;
  57495. if (this._connectedMesh) {
  57496. this._updateDirection();
  57497. }
  57498. else {
  57499. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  57500. }
  57501. }
  57502. }
  57503. }
  57504. if (this._streaming) {
  57505. if (!this._streamingSource) {
  57506. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  57507. this._htmlAudioElement.onended = function () { _this._onended(); };
  57508. this._htmlAudioElement.playbackRate = this._playbackRate;
  57509. }
  57510. this._streamingSource.disconnect();
  57511. this._streamingSource.connect(this._inputAudioNode);
  57512. this._htmlAudioElement.play();
  57513. }
  57514. else {
  57515. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  57516. this._soundSource.buffer = this._audioBuffer;
  57517. this._soundSource.connect(this._inputAudioNode);
  57518. this._soundSource.loop = this.loop;
  57519. this._soundSource.playbackRate.value = this._playbackRate;
  57520. this._soundSource.onended = function () { _this._onended(); };
  57521. if (this._soundSource.buffer) {
  57522. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  57523. }
  57524. }
  57525. this._startTime = startTime;
  57526. this.isPlaying = true;
  57527. this.isPaused = false;
  57528. }
  57529. catch (ex) {
  57530. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  57531. }
  57532. }
  57533. };
  57534. Sound.prototype._onended = function () {
  57535. this.isPlaying = false;
  57536. if (this.onended) {
  57537. this.onended();
  57538. }
  57539. };
  57540. /**
  57541. * Stop the sound
  57542. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  57543. */
  57544. Sound.prototype.stop = function (time) {
  57545. if (this.isPlaying) {
  57546. if (this._streaming) {
  57547. this._htmlAudioElement.pause();
  57548. // Test needed for Firefox or it will generate an Invalid State Error
  57549. if (this._htmlAudioElement.currentTime > 0) {
  57550. this._htmlAudioElement.currentTime = 0;
  57551. }
  57552. }
  57553. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  57554. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  57555. this._soundSource.stop(stopTime);
  57556. this._soundSource.onended = function () { };
  57557. if (!this.isPaused) {
  57558. this._startOffset = 0;
  57559. }
  57560. }
  57561. this.isPlaying = false;
  57562. }
  57563. };
  57564. Sound.prototype.pause = function () {
  57565. if (this.isPlaying) {
  57566. this.isPaused = true;
  57567. if (this._streaming) {
  57568. this._htmlAudioElement.pause();
  57569. }
  57570. else if (BABYLON.Engine.audioEngine.audioContext) {
  57571. this.stop(0);
  57572. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  57573. }
  57574. }
  57575. };
  57576. Sound.prototype.setVolume = function (newVolume, time) {
  57577. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  57578. if (time && BABYLON.Engine.audioEngine.audioContext) {
  57579. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  57580. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  57581. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  57582. }
  57583. else {
  57584. this._soundGain.gain.value = newVolume;
  57585. }
  57586. }
  57587. this._volume = newVolume;
  57588. };
  57589. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  57590. this._playbackRate = newPlaybackRate;
  57591. if (this.isPlaying) {
  57592. if (this._streaming) {
  57593. this._htmlAudioElement.playbackRate = this._playbackRate;
  57594. }
  57595. else if (this._soundSource) {
  57596. this._soundSource.playbackRate.value = this._playbackRate;
  57597. }
  57598. }
  57599. };
  57600. Sound.prototype.getVolume = function () {
  57601. return this._volume;
  57602. };
  57603. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  57604. var _this = this;
  57605. if (this._connectedMesh && this._registerFunc) {
  57606. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57607. this._registerFunc = null;
  57608. }
  57609. this._connectedMesh = meshToConnectTo;
  57610. if (!this.spatialSound) {
  57611. this.spatialSound = true;
  57612. this._createSpatialParameters();
  57613. if (this.isPlaying && this.loop) {
  57614. this.stop();
  57615. this.play();
  57616. }
  57617. }
  57618. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  57619. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  57620. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  57621. };
  57622. Sound.prototype.detachFromMesh = function () {
  57623. if (this._connectedMesh && this._registerFunc) {
  57624. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57625. this._registerFunc = null;
  57626. this._connectedMesh = null;
  57627. }
  57628. };
  57629. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  57630. if (!node.getBoundingInfo) {
  57631. return;
  57632. }
  57633. var mesh = node;
  57634. var boundingInfo = mesh.getBoundingInfo();
  57635. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  57636. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  57637. this._updateDirection();
  57638. }
  57639. };
  57640. Sound.prototype.clone = function () {
  57641. var _this = this;
  57642. if (!this._streaming) {
  57643. var setBufferAndRun = function () {
  57644. if (_this._isReadyToPlay) {
  57645. clonedSound._audioBuffer = _this.getAudioBuffer();
  57646. clonedSound._isReadyToPlay = true;
  57647. if (clonedSound.autoplay) {
  57648. clonedSound.play();
  57649. }
  57650. }
  57651. else {
  57652. window.setTimeout(setBufferAndRun, 300);
  57653. }
  57654. };
  57655. var currentOptions = {
  57656. autoplay: this.autoplay, loop: this.loop,
  57657. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  57658. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  57659. refDistance: this.refDistance, distanceModel: this.distanceModel
  57660. };
  57661. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  57662. if (this.useCustomAttenuation) {
  57663. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  57664. }
  57665. clonedSound.setPosition(this._position);
  57666. clonedSound.setPlaybackRate(this._playbackRate);
  57667. setBufferAndRun();
  57668. return clonedSound;
  57669. }
  57670. else {
  57671. return null;
  57672. }
  57673. };
  57674. Sound.prototype.getAudioBuffer = function () {
  57675. return this._audioBuffer;
  57676. };
  57677. Sound.prototype.serialize = function () {
  57678. var serializationObject = {
  57679. name: this.name,
  57680. url: this.name,
  57681. autoplay: this.autoplay,
  57682. loop: this.loop,
  57683. volume: this._volume,
  57684. spatialSound: this.spatialSound,
  57685. maxDistance: this.maxDistance,
  57686. rolloffFactor: this.rolloffFactor,
  57687. refDistance: this.refDistance,
  57688. distanceModel: this.distanceModel,
  57689. playbackRate: this._playbackRate,
  57690. panningModel: this._panningModel,
  57691. soundTrackId: this.soundTrackId
  57692. };
  57693. if (this.spatialSound) {
  57694. if (this._connectedMesh)
  57695. serializationObject.connectedMeshId = this._connectedMesh.id;
  57696. serializationObject.position = this._position.asArray();
  57697. serializationObject.refDistance = this.refDistance;
  57698. serializationObject.distanceModel = this.distanceModel;
  57699. serializationObject.isDirectional = this._isDirectional;
  57700. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  57701. serializationObject.coneInnerAngle = this._coneInnerAngle;
  57702. serializationObject.coneOuterAngle = this._coneOuterAngle;
  57703. serializationObject.coneOuterGain = this._coneOuterGain;
  57704. }
  57705. return serializationObject;
  57706. };
  57707. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  57708. var soundName = parsedSound.name;
  57709. var soundUrl;
  57710. if (parsedSound.url) {
  57711. soundUrl = rootUrl + parsedSound.url;
  57712. }
  57713. else {
  57714. soundUrl = rootUrl + soundName;
  57715. }
  57716. var options = {
  57717. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  57718. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  57719. rolloffFactor: parsedSound.rolloffFactor,
  57720. refDistance: parsedSound.refDistance,
  57721. distanceModel: parsedSound.distanceModel,
  57722. playbackRate: parsedSound.playbackRate
  57723. };
  57724. var newSound;
  57725. if (!sourceSound) {
  57726. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  57727. scene._addPendingData(newSound);
  57728. }
  57729. else {
  57730. var setBufferAndRun = function () {
  57731. if (sourceSound._isReadyToPlay) {
  57732. newSound._audioBuffer = sourceSound.getAudioBuffer();
  57733. newSound._isReadyToPlay = true;
  57734. if (newSound.autoplay) {
  57735. newSound.play();
  57736. }
  57737. }
  57738. else {
  57739. window.setTimeout(setBufferAndRun, 300);
  57740. }
  57741. };
  57742. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  57743. setBufferAndRun();
  57744. }
  57745. if (parsedSound.position) {
  57746. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  57747. newSound.setPosition(soundPosition);
  57748. }
  57749. if (parsedSound.isDirectional) {
  57750. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  57751. if (parsedSound.localDirectionToMesh) {
  57752. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  57753. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  57754. }
  57755. }
  57756. if (parsedSound.connectedMeshId) {
  57757. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  57758. if (connectedMesh) {
  57759. newSound.attachToMesh(connectedMesh);
  57760. }
  57761. }
  57762. return newSound;
  57763. };
  57764. return Sound;
  57765. }());
  57766. BABYLON.Sound = Sound;
  57767. })(BABYLON || (BABYLON = {}));
  57768. //# sourceMappingURL=babylon.sound.js.map
  57769. "use strict";
  57770. var BABYLON;
  57771. (function (BABYLON) {
  57772. var SoundTrack = /** @class */ (function () {
  57773. function SoundTrack(scene, options) {
  57774. this.id = -1;
  57775. this._isMainTrack = false;
  57776. this._isInitialized = false;
  57777. this._scene = scene;
  57778. this.soundCollection = new Array();
  57779. this._options = options;
  57780. if (!this._isMainTrack) {
  57781. this._scene.soundTracks.push(this);
  57782. this.id = this._scene.soundTracks.length - 1;
  57783. }
  57784. }
  57785. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  57786. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57787. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  57788. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  57789. if (this._options) {
  57790. if (this._options.volume) {
  57791. this._outputAudioNode.gain.value = this._options.volume;
  57792. }
  57793. if (this._options.mainTrack) {
  57794. this._isMainTrack = this._options.mainTrack;
  57795. }
  57796. }
  57797. this._isInitialized = true;
  57798. }
  57799. };
  57800. SoundTrack.prototype.dispose = function () {
  57801. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  57802. if (this._connectedAnalyser) {
  57803. this._connectedAnalyser.stopDebugCanvas();
  57804. }
  57805. while (this.soundCollection.length) {
  57806. this.soundCollection[0].dispose();
  57807. }
  57808. if (this._outputAudioNode) {
  57809. this._outputAudioNode.disconnect();
  57810. }
  57811. this._outputAudioNode = null;
  57812. }
  57813. };
  57814. SoundTrack.prototype.AddSound = function (sound) {
  57815. if (!this._isInitialized) {
  57816. this._initializeSoundTrackAudioGraph();
  57817. }
  57818. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57819. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  57820. }
  57821. if (sound.soundTrackId) {
  57822. if (sound.soundTrackId === -1) {
  57823. this._scene.mainSoundTrack.RemoveSound(sound);
  57824. }
  57825. else {
  57826. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  57827. }
  57828. }
  57829. this.soundCollection.push(sound);
  57830. sound.soundTrackId = this.id;
  57831. };
  57832. SoundTrack.prototype.RemoveSound = function (sound) {
  57833. var index = this.soundCollection.indexOf(sound);
  57834. if (index !== -1) {
  57835. this.soundCollection.splice(index, 1);
  57836. }
  57837. };
  57838. SoundTrack.prototype.setVolume = function (newVolume) {
  57839. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57840. this._outputAudioNode.gain.value = newVolume;
  57841. }
  57842. };
  57843. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  57844. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57845. for (var i = 0; i < this.soundCollection.length; i++) {
  57846. this.soundCollection[i].switchPanningModelToHRTF();
  57847. }
  57848. }
  57849. };
  57850. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  57851. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57852. for (var i = 0; i < this.soundCollection.length; i++) {
  57853. this.soundCollection[i].switchPanningModelToEqualPower();
  57854. }
  57855. }
  57856. };
  57857. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  57858. if (this._connectedAnalyser) {
  57859. this._connectedAnalyser.stopDebugCanvas();
  57860. }
  57861. this._connectedAnalyser = analyser;
  57862. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57863. this._outputAudioNode.disconnect();
  57864. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  57865. }
  57866. };
  57867. return SoundTrack;
  57868. }());
  57869. BABYLON.SoundTrack = SoundTrack;
  57870. })(BABYLON || (BABYLON = {}));
  57871. //# sourceMappingURL=babylon.soundtrack.js.map
  57872. "use strict";
  57873. var BABYLON;
  57874. (function (BABYLON) {
  57875. var Analyser = /** @class */ (function () {
  57876. function Analyser(scene) {
  57877. this.SMOOTHING = 0.75;
  57878. this.FFT_SIZE = 512;
  57879. this.BARGRAPHAMPLITUDE = 256;
  57880. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  57881. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  57882. this._scene = scene;
  57883. this._audioEngine = BABYLON.Engine.audioEngine;
  57884. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  57885. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  57886. this._webAudioAnalyser.minDecibels = -140;
  57887. this._webAudioAnalyser.maxDecibels = 0;
  57888. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57889. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57890. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  57891. }
  57892. }
  57893. Analyser.prototype.getFrequencyBinCount = function () {
  57894. if (this._audioEngine.canUseWebAudio) {
  57895. return this._webAudioAnalyser.frequencyBinCount;
  57896. }
  57897. else {
  57898. return 0;
  57899. }
  57900. };
  57901. Analyser.prototype.getByteFrequencyData = function () {
  57902. if (this._audioEngine.canUseWebAudio) {
  57903. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57904. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57905. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  57906. }
  57907. return this._byteFreqs;
  57908. };
  57909. Analyser.prototype.getByteTimeDomainData = function () {
  57910. if (this._audioEngine.canUseWebAudio) {
  57911. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57912. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57913. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  57914. }
  57915. return this._byteTime;
  57916. };
  57917. Analyser.prototype.getFloatFrequencyData = function () {
  57918. if (this._audioEngine.canUseWebAudio) {
  57919. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57920. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57921. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  57922. }
  57923. return this._floatFreqs;
  57924. };
  57925. Analyser.prototype.drawDebugCanvas = function () {
  57926. var _this = this;
  57927. if (this._audioEngine.canUseWebAudio) {
  57928. if (!this._debugCanvas) {
  57929. this._debugCanvas = document.createElement("canvas");
  57930. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  57931. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  57932. this._debugCanvas.style.position = "absolute";
  57933. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  57934. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  57935. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  57936. document.body.appendChild(this._debugCanvas);
  57937. this._registerFunc = function () {
  57938. _this.drawDebugCanvas();
  57939. };
  57940. this._scene.registerBeforeRender(this._registerFunc);
  57941. }
  57942. if (this._registerFunc && this._debugCanvasContext) {
  57943. var workingArray = this.getByteFrequencyData();
  57944. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  57945. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  57946. // Draw the frequency domain chart.
  57947. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  57948. var value = workingArray[i];
  57949. var percent = value / this.BARGRAPHAMPLITUDE;
  57950. var height = this.DEBUGCANVASSIZE.height * percent;
  57951. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  57952. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  57953. var hue = i / this.getFrequencyBinCount() * 360;
  57954. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  57955. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  57956. }
  57957. }
  57958. }
  57959. };
  57960. Analyser.prototype.stopDebugCanvas = function () {
  57961. if (this._debugCanvas) {
  57962. if (this._registerFunc) {
  57963. this._scene.unregisterBeforeRender(this._registerFunc);
  57964. this._registerFunc = null;
  57965. }
  57966. document.body.removeChild(this._debugCanvas);
  57967. this._debugCanvas = null;
  57968. this._debugCanvasContext = null;
  57969. }
  57970. };
  57971. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  57972. if (this._audioEngine.canUseWebAudio) {
  57973. inputAudioNode.connect(this._webAudioAnalyser);
  57974. this._webAudioAnalyser.connect(outputAudioNode);
  57975. }
  57976. };
  57977. Analyser.prototype.dispose = function () {
  57978. if (this._audioEngine.canUseWebAudio) {
  57979. this._webAudioAnalyser.disconnect();
  57980. }
  57981. };
  57982. return Analyser;
  57983. }());
  57984. BABYLON.Analyser = Analyser;
  57985. })(BABYLON || (BABYLON = {}));
  57986. //# sourceMappingURL=babylon.analyser.js.map
  57987. "use strict";
  57988. var BABYLON;
  57989. (function (BABYLON) {
  57990. var CubeTexture = /** @class */ (function (_super) {
  57991. __extends(CubeTexture, _super);
  57992. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  57993. if (extensions === void 0) { extensions = null; }
  57994. if (noMipmap === void 0) { noMipmap = false; }
  57995. if (files === void 0) { files = null; }
  57996. if (onLoad === void 0) { onLoad = null; }
  57997. if (onError === void 0) { onError = null; }
  57998. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  57999. if (prefiltered === void 0) { prefiltered = false; }
  58000. if (forcedExtension === void 0) { forcedExtension = null; }
  58001. var _this = _super.call(this, scene) || this;
  58002. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  58003. /**
  58004. * Gets or sets the center of the bounding box associated with the cube texture
  58005. * It must define where the camera used to render the texture was set
  58006. */
  58007. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58008. _this.name = rootUrl;
  58009. _this.url = rootUrl;
  58010. _this._noMipmap = noMipmap;
  58011. _this.hasAlpha = false;
  58012. _this._format = format;
  58013. _this._prefiltered = prefiltered;
  58014. _this.isCube = true;
  58015. _this._textureMatrix = BABYLON.Matrix.Identity();
  58016. if (prefiltered) {
  58017. _this.gammaSpace = false;
  58018. }
  58019. if (!rootUrl && !files) {
  58020. return _this;
  58021. }
  58022. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  58023. var lastDot = rootUrl.lastIndexOf(".");
  58024. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  58025. var isDDS = (extension === ".dds");
  58026. if (!files) {
  58027. if (!isDDS && !extensions) {
  58028. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  58029. }
  58030. files = [];
  58031. if (extensions) {
  58032. for (var index = 0; index < extensions.length; index++) {
  58033. files.push(rootUrl + extensions[index]);
  58034. }
  58035. }
  58036. }
  58037. _this._files = files;
  58038. if (!_this._texture) {
  58039. if (!scene.useDelayedTextureLoading) {
  58040. if (prefiltered) {
  58041. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  58042. }
  58043. else {
  58044. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  58045. }
  58046. }
  58047. else {
  58048. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  58049. }
  58050. }
  58051. else if (onLoad) {
  58052. if (_this._texture.isReady) {
  58053. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  58054. }
  58055. else {
  58056. _this._texture.onLoadedObservable.add(onLoad);
  58057. }
  58058. }
  58059. return _this;
  58060. }
  58061. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  58062. get: function () {
  58063. return this._boundingBoxSize;
  58064. },
  58065. /**
  58066. * Gets or sets the size of the bounding box associated with the cube texture
  58067. * When defined, the cubemap will switch to local mode
  58068. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  58069. * @example https://www.babylonjs-playground.com/#RNASML
  58070. */
  58071. set: function (value) {
  58072. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  58073. return;
  58074. }
  58075. this._boundingBoxSize = value;
  58076. var scene = this.getScene();
  58077. if (scene) {
  58078. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  58079. }
  58080. },
  58081. enumerable: true,
  58082. configurable: true
  58083. });
  58084. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  58085. var rootUrlKey = "";
  58086. files.forEach(function (url) { return rootUrlKey += url; });
  58087. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  58088. };
  58089. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  58090. if (forcedExtension === void 0) { forcedExtension = null; }
  58091. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  58092. };
  58093. // Methods
  58094. CubeTexture.prototype.delayLoad = function () {
  58095. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  58096. return;
  58097. }
  58098. var scene = this.getScene();
  58099. if (!scene) {
  58100. return;
  58101. }
  58102. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  58103. this._texture = this._getFromCache(this.url, this._noMipmap);
  58104. if (!this._texture) {
  58105. if (this._prefiltered) {
  58106. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  58107. }
  58108. else {
  58109. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  58110. }
  58111. }
  58112. };
  58113. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  58114. return this._textureMatrix;
  58115. };
  58116. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  58117. this._textureMatrix = value;
  58118. };
  58119. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  58120. var texture = BABYLON.SerializationHelper.Parse(function () {
  58121. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  58122. }, parsedTexture, scene);
  58123. // Local Cubemaps
  58124. if (parsedTexture.boundingBoxPosition) {
  58125. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  58126. }
  58127. if (parsedTexture.boundingBoxSize) {
  58128. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  58129. }
  58130. // Animations
  58131. if (parsedTexture.animations) {
  58132. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  58133. var parsedAnimation = parsedTexture.animations[animationIndex];
  58134. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58135. }
  58136. }
  58137. return texture;
  58138. };
  58139. CubeTexture.prototype.clone = function () {
  58140. var _this = this;
  58141. return BABYLON.SerializationHelper.Clone(function () {
  58142. var scene = _this.getScene();
  58143. if (!scene) {
  58144. return _this;
  58145. }
  58146. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  58147. }, this);
  58148. };
  58149. return CubeTexture;
  58150. }(BABYLON.BaseTexture));
  58151. BABYLON.CubeTexture = CubeTexture;
  58152. })(BABYLON || (BABYLON = {}));
  58153. //# sourceMappingURL=babylon.cubeTexture.js.map
  58154. "use strict";
  58155. var BABYLON;
  58156. (function (BABYLON) {
  58157. var RenderTargetTexture = /** @class */ (function (_super) {
  58158. __extends(RenderTargetTexture, _super);
  58159. /**
  58160. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  58161. * or used a shadow, depth texture...
  58162. * @param name The friendly name of the texture
  58163. * @param size The size of the RTT (number if square, or {with: number, height:number} or {ratio:} to define a ratio from the main scene)
  58164. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  58165. * @param generateMipMaps True if mip maps need to be generated after render.
  58166. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  58167. * @param type The type of the buffer in the RTT (int, half float, float...)
  58168. * @param isCube True if a cube texture needs to be created
  58169. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  58170. * @param generateDepthBuffer True to generate a depth buffer
  58171. * @param generateStencilBuffer True to generate a stencil buffer
  58172. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  58173. */
  58174. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  58175. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  58176. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58177. if (isCube === void 0) { isCube = false; }
  58178. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58179. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58180. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  58181. if (isMulti === void 0) { isMulti = false; }
  58182. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  58183. _this.isCube = isCube;
  58184. /**
  58185. * Use this list to define the list of mesh you want to render.
  58186. */
  58187. _this.renderList = new Array();
  58188. _this.renderParticles = true;
  58189. _this.renderSprites = false;
  58190. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  58191. _this.ignoreCameraViewport = false;
  58192. // Events
  58193. /**
  58194. * An event triggered when the texture is unbind.
  58195. * @type {BABYLON.Observable}
  58196. */
  58197. _this.onBeforeBindObservable = new BABYLON.Observable();
  58198. /**
  58199. * An event triggered when the texture is unbind.
  58200. * @type {BABYLON.Observable}
  58201. */
  58202. _this.onAfterUnbindObservable = new BABYLON.Observable();
  58203. /**
  58204. * An event triggered before rendering the texture
  58205. * @type {BABYLON.Observable}
  58206. */
  58207. _this.onBeforeRenderObservable = new BABYLON.Observable();
  58208. /**
  58209. * An event triggered after rendering the texture
  58210. * @type {BABYLON.Observable}
  58211. */
  58212. _this.onAfterRenderObservable = new BABYLON.Observable();
  58213. /**
  58214. * An event triggered after the texture clear
  58215. * @type {BABYLON.Observable}
  58216. */
  58217. _this.onClearObservable = new BABYLON.Observable();
  58218. _this._currentRefreshId = -1;
  58219. _this._refreshRate = 1;
  58220. _this._samples = 1;
  58221. /**
  58222. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  58223. * It must define where the camera used to render the texture is set
  58224. */
  58225. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58226. scene = _this.getScene();
  58227. if (!scene) {
  58228. return _this;
  58229. }
  58230. _this._engine = scene.getEngine();
  58231. _this.name = name;
  58232. _this.isRenderTarget = true;
  58233. _this._initialSizeParameter = size;
  58234. _this._processSizeParameter(size);
  58235. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  58236. });
  58237. _this._generateMipMaps = generateMipMaps ? true : false;
  58238. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  58239. // Rendering groups
  58240. _this._renderingManager = new BABYLON.RenderingManager(scene);
  58241. if (isMulti) {
  58242. return _this;
  58243. }
  58244. _this._renderTargetOptions = {
  58245. generateMipMaps: generateMipMaps,
  58246. type: type,
  58247. samplingMode: samplingMode,
  58248. generateDepthBuffer: generateDepthBuffer,
  58249. generateStencilBuffer: generateStencilBuffer
  58250. };
  58251. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  58252. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58253. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58254. }
  58255. if (isCube) {
  58256. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  58257. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  58258. _this._textureMatrix = BABYLON.Matrix.Identity();
  58259. }
  58260. else {
  58261. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  58262. }
  58263. return _this;
  58264. }
  58265. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  58266. get: function () {
  58267. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  58268. },
  58269. enumerable: true,
  58270. configurable: true
  58271. });
  58272. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  58273. get: function () {
  58274. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  58275. },
  58276. enumerable: true,
  58277. configurable: true
  58278. });
  58279. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  58280. get: function () {
  58281. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  58282. },
  58283. enumerable: true,
  58284. configurable: true
  58285. });
  58286. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  58287. set: function (callback) {
  58288. if (this._onAfterUnbindObserver) {
  58289. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  58290. }
  58291. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  58292. },
  58293. enumerable: true,
  58294. configurable: true
  58295. });
  58296. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  58297. set: function (callback) {
  58298. if (this._onBeforeRenderObserver) {
  58299. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  58300. }
  58301. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  58302. },
  58303. enumerable: true,
  58304. configurable: true
  58305. });
  58306. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  58307. set: function (callback) {
  58308. if (this._onAfterRenderObserver) {
  58309. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  58310. }
  58311. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  58312. },
  58313. enumerable: true,
  58314. configurable: true
  58315. });
  58316. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  58317. set: function (callback) {
  58318. if (this._onClearObserver) {
  58319. this.onClearObservable.remove(this._onClearObserver);
  58320. }
  58321. this._onClearObserver = this.onClearObservable.add(callback);
  58322. },
  58323. enumerable: true,
  58324. configurable: true
  58325. });
  58326. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  58327. get: function () {
  58328. return this._renderTargetOptions;
  58329. },
  58330. enumerable: true,
  58331. configurable: true
  58332. });
  58333. RenderTargetTexture.prototype._onRatioRescale = function () {
  58334. if (this._sizeRatio) {
  58335. this.resize(this._initialSizeParameter);
  58336. }
  58337. };
  58338. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  58339. get: function () {
  58340. return this._boundingBoxSize;
  58341. },
  58342. /**
  58343. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  58344. * When defined, the cubemap will switch to local mode
  58345. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  58346. * @example https://www.babylonjs-playground.com/#RNASML
  58347. */
  58348. set: function (value) {
  58349. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  58350. return;
  58351. }
  58352. this._boundingBoxSize = value;
  58353. var scene = this.getScene();
  58354. if (scene) {
  58355. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  58356. }
  58357. },
  58358. enumerable: true,
  58359. configurable: true
  58360. });
  58361. /**
  58362. * Creates a depth stencil texture.
  58363. * This is only available in WebGL 2 or with the depth texture extension available.
  58364. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  58365. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  58366. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  58367. */
  58368. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  58369. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  58370. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  58371. if (generateStencil === void 0) { generateStencil = false; }
  58372. if (!this.getScene()) {
  58373. return;
  58374. }
  58375. var engine = this.getScene().getEngine();
  58376. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  58377. bilinearFiltering: bilinearFiltering,
  58378. comparisonFunction: comparisonFunction,
  58379. generateStencil: generateStencil,
  58380. isCube: this.isCube
  58381. });
  58382. engine.setFrameBufferDepthStencilTexture(this);
  58383. };
  58384. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  58385. if (size.ratio) {
  58386. this._sizeRatio = size.ratio;
  58387. this._size = {
  58388. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  58389. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  58390. };
  58391. }
  58392. else {
  58393. this._size = size;
  58394. }
  58395. };
  58396. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  58397. get: function () {
  58398. return this._samples;
  58399. },
  58400. set: function (value) {
  58401. if (this._samples === value) {
  58402. return;
  58403. }
  58404. var scene = this.getScene();
  58405. if (!scene) {
  58406. return;
  58407. }
  58408. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  58409. },
  58410. enumerable: true,
  58411. configurable: true
  58412. });
  58413. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  58414. this._currentRefreshId = -1;
  58415. };
  58416. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  58417. get: function () {
  58418. return this._refreshRate;
  58419. },
  58420. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  58421. set: function (value) {
  58422. this._refreshRate = value;
  58423. this.resetRefreshCounter();
  58424. },
  58425. enumerable: true,
  58426. configurable: true
  58427. });
  58428. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  58429. if (!this._postProcessManager) {
  58430. var scene = this.getScene();
  58431. if (!scene) {
  58432. return;
  58433. }
  58434. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  58435. this._postProcesses = new Array();
  58436. }
  58437. this._postProcesses.push(postProcess);
  58438. this._postProcesses[0].autoClear = false;
  58439. };
  58440. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  58441. if (!this._postProcesses) {
  58442. return;
  58443. }
  58444. if (dispose) {
  58445. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  58446. var postProcess = _a[_i];
  58447. postProcess.dispose();
  58448. }
  58449. }
  58450. this._postProcesses = [];
  58451. };
  58452. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  58453. if (!this._postProcesses) {
  58454. return;
  58455. }
  58456. var index = this._postProcesses.indexOf(postProcess);
  58457. if (index === -1) {
  58458. return;
  58459. }
  58460. this._postProcesses.splice(index, 1);
  58461. if (this._postProcesses.length > 0) {
  58462. this._postProcesses[0].autoClear = false;
  58463. }
  58464. };
  58465. RenderTargetTexture.prototype._shouldRender = function () {
  58466. if (this._currentRefreshId === -1) {
  58467. this._currentRefreshId = 1;
  58468. return true;
  58469. }
  58470. if (this.refreshRate === this._currentRefreshId) {
  58471. this._currentRefreshId = 1;
  58472. return true;
  58473. }
  58474. this._currentRefreshId++;
  58475. return false;
  58476. };
  58477. RenderTargetTexture.prototype.getRenderSize = function () {
  58478. if (this._size.width) {
  58479. return this._size.width;
  58480. }
  58481. return this._size;
  58482. };
  58483. RenderTargetTexture.prototype.getRenderWidth = function () {
  58484. if (this._size.width) {
  58485. return this._size.width;
  58486. }
  58487. return this._size;
  58488. };
  58489. RenderTargetTexture.prototype.getRenderHeight = function () {
  58490. if (this._size.width) {
  58491. return this._size.height;
  58492. }
  58493. return this._size;
  58494. };
  58495. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  58496. get: function () {
  58497. return true;
  58498. },
  58499. enumerable: true,
  58500. configurable: true
  58501. });
  58502. RenderTargetTexture.prototype.scale = function (ratio) {
  58503. var newSize = this.getRenderSize() * ratio;
  58504. this.resize(newSize);
  58505. };
  58506. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  58507. if (this.isCube) {
  58508. return this._textureMatrix;
  58509. }
  58510. return _super.prototype.getReflectionTextureMatrix.call(this);
  58511. };
  58512. RenderTargetTexture.prototype.resize = function (size) {
  58513. this.releaseInternalTexture();
  58514. var scene = this.getScene();
  58515. if (!scene) {
  58516. return;
  58517. }
  58518. this._processSizeParameter(size);
  58519. if (this.isCube) {
  58520. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  58521. }
  58522. else {
  58523. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  58524. }
  58525. };
  58526. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  58527. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  58528. if (dumpForDebug === void 0) { dumpForDebug = false; }
  58529. var scene = this.getScene();
  58530. if (!scene) {
  58531. return;
  58532. }
  58533. var engine = scene.getEngine();
  58534. if (this.useCameraPostProcesses !== undefined) {
  58535. useCameraPostProcess = this.useCameraPostProcesses;
  58536. }
  58537. if (this._waitingRenderList) {
  58538. this.renderList = [];
  58539. for (var index = 0; index < this._waitingRenderList.length; index++) {
  58540. var id = this._waitingRenderList[index];
  58541. var mesh_1 = scene.getMeshByID(id);
  58542. if (mesh_1) {
  58543. this.renderList.push(mesh_1);
  58544. }
  58545. }
  58546. delete this._waitingRenderList;
  58547. }
  58548. // Is predicate defined?
  58549. if (this.renderListPredicate) {
  58550. if (this.renderList) {
  58551. this.renderList.splice(0); // Clear previous renderList
  58552. }
  58553. else {
  58554. this.renderList = [];
  58555. }
  58556. var scene = this.getScene();
  58557. if (!scene) {
  58558. return;
  58559. }
  58560. var sceneMeshes = scene.meshes;
  58561. for (var index = 0; index < sceneMeshes.length; index++) {
  58562. var mesh = sceneMeshes[index];
  58563. if (this.renderListPredicate(mesh)) {
  58564. this.renderList.push(mesh);
  58565. }
  58566. }
  58567. }
  58568. this.onBeforeBindObservable.notifyObservers(this);
  58569. // Set custom projection.
  58570. // Needs to be before binding to prevent changing the aspect ratio.
  58571. var camera;
  58572. if (this.activeCamera) {
  58573. camera = this.activeCamera;
  58574. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  58575. if (this.activeCamera !== scene.activeCamera) {
  58576. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  58577. }
  58578. }
  58579. else {
  58580. camera = scene.activeCamera;
  58581. if (camera) {
  58582. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  58583. }
  58584. }
  58585. // Prepare renderingManager
  58586. this._renderingManager.reset();
  58587. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  58588. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  58589. var sceneRenderId = scene.getRenderId();
  58590. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  58591. var mesh = currentRenderList[meshIndex];
  58592. if (mesh) {
  58593. if (!mesh.isReady(this.refreshRate === 0)) {
  58594. this.resetRefreshCounter();
  58595. continue;
  58596. }
  58597. mesh._preActivateForIntermediateRendering(sceneRenderId);
  58598. var isMasked = void 0;
  58599. if (!this.renderList && camera) {
  58600. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  58601. }
  58602. else {
  58603. isMasked = false;
  58604. }
  58605. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  58606. mesh._activate(sceneRenderId);
  58607. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  58608. var subMesh = mesh.subMeshes[subIndex];
  58609. scene._activeIndices.addCount(subMesh.indexCount, false);
  58610. this._renderingManager.dispatch(subMesh, mesh);
  58611. }
  58612. }
  58613. }
  58614. }
  58615. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  58616. var particleSystem = scene.particleSystems[particleIndex];
  58617. var emitter = particleSystem.emitter;
  58618. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  58619. continue;
  58620. }
  58621. if (currentRenderList.indexOf(emitter) >= 0) {
  58622. this._renderingManager.dispatchParticles(particleSystem);
  58623. }
  58624. }
  58625. if (this.isCube) {
  58626. for (var face = 0; face < 6; face++) {
  58627. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  58628. scene.incrementRenderId();
  58629. scene.resetCachedMaterial();
  58630. }
  58631. }
  58632. else {
  58633. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  58634. }
  58635. this.onAfterUnbindObservable.notifyObservers(this);
  58636. if (scene.activeCamera) {
  58637. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  58638. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  58639. }
  58640. engine.setViewport(scene.activeCamera.viewport);
  58641. }
  58642. scene.resetCachedMaterial();
  58643. };
  58644. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  58645. var minimum = 128;
  58646. var x = renderDimension * scale;
  58647. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  58648. // Ensure we don't exceed the render dimension (while staying POT)
  58649. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  58650. };
  58651. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  58652. var _this = this;
  58653. if (!this._texture) {
  58654. return;
  58655. }
  58656. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  58657. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  58658. });
  58659. };
  58660. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  58661. var scene = this.getScene();
  58662. if (!scene) {
  58663. return;
  58664. }
  58665. var engine = scene.getEngine();
  58666. if (!this._texture) {
  58667. return;
  58668. }
  58669. // Bind
  58670. if (this._postProcessManager) {
  58671. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  58672. }
  58673. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  58674. if (this._texture) {
  58675. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  58676. }
  58677. }
  58678. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  58679. // Clear
  58680. if (this.onClearObservable.hasObservers()) {
  58681. this.onClearObservable.notifyObservers(engine);
  58682. }
  58683. else {
  58684. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  58685. }
  58686. if (!this._doNotChangeAspectRatio) {
  58687. scene.updateTransformMatrix(true);
  58688. }
  58689. // Render
  58690. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  58691. if (this._postProcessManager) {
  58692. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  58693. }
  58694. else if (useCameraPostProcess) {
  58695. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  58696. }
  58697. if (!this._doNotChangeAspectRatio) {
  58698. scene.updateTransformMatrix(true);
  58699. }
  58700. // Dump ?
  58701. if (dumpForDebug) {
  58702. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  58703. }
  58704. // Unbind
  58705. if (!this.isCube || faceIndex === 5) {
  58706. if (this.isCube) {
  58707. if (faceIndex === 5) {
  58708. engine.generateMipMapsForCubemap(this._texture);
  58709. }
  58710. }
  58711. this.unbindFrameBuffer(engine, faceIndex);
  58712. }
  58713. else {
  58714. this.onAfterRenderObservable.notifyObservers(faceIndex);
  58715. }
  58716. };
  58717. /**
  58718. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  58719. * This allowed control for front to back rendering or reversly depending of the special needs.
  58720. *
  58721. * @param renderingGroupId The rendering group id corresponding to its index
  58722. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  58723. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  58724. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  58725. */
  58726. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  58727. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  58728. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  58729. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  58730. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  58731. };
  58732. /**
  58733. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  58734. *
  58735. * @param renderingGroupId The rendering group id corresponding to its index
  58736. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  58737. */
  58738. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  58739. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  58740. };
  58741. RenderTargetTexture.prototype.clone = function () {
  58742. var textureSize = this.getSize();
  58743. 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);
  58744. // Base texture
  58745. newTexture.hasAlpha = this.hasAlpha;
  58746. newTexture.level = this.level;
  58747. // RenderTarget Texture
  58748. newTexture.coordinatesMode = this.coordinatesMode;
  58749. if (this.renderList) {
  58750. newTexture.renderList = this.renderList.slice(0);
  58751. }
  58752. return newTexture;
  58753. };
  58754. RenderTargetTexture.prototype.serialize = function () {
  58755. if (!this.name) {
  58756. return null;
  58757. }
  58758. var serializationObject = _super.prototype.serialize.call(this);
  58759. serializationObject.renderTargetSize = this.getRenderSize();
  58760. serializationObject.renderList = [];
  58761. if (this.renderList) {
  58762. for (var index = 0; index < this.renderList.length; index++) {
  58763. serializationObject.renderList.push(this.renderList[index].id);
  58764. }
  58765. }
  58766. return serializationObject;
  58767. };
  58768. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  58769. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  58770. var objBuffer = this.getInternalTexture();
  58771. var scene = this.getScene();
  58772. if (objBuffer && scene) {
  58773. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  58774. }
  58775. };
  58776. RenderTargetTexture.prototype.dispose = function () {
  58777. if (this._postProcessManager) {
  58778. this._postProcessManager.dispose();
  58779. this._postProcessManager = null;
  58780. }
  58781. this.clearPostProcesses(true);
  58782. if (this._resizeObserver) {
  58783. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  58784. this._resizeObserver = null;
  58785. }
  58786. this.renderList = null;
  58787. // Remove from custom render targets
  58788. var scene = this.getScene();
  58789. if (!scene) {
  58790. return;
  58791. }
  58792. var index = scene.customRenderTargets.indexOf(this);
  58793. if (index >= 0) {
  58794. scene.customRenderTargets.splice(index, 1);
  58795. }
  58796. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  58797. var camera = _a[_i];
  58798. index = camera.customRenderTargets.indexOf(this);
  58799. if (index >= 0) {
  58800. camera.customRenderTargets.splice(index, 1);
  58801. }
  58802. }
  58803. _super.prototype.dispose.call(this);
  58804. };
  58805. RenderTargetTexture.prototype._rebuild = function () {
  58806. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  58807. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  58808. }
  58809. if (this._postProcessManager) {
  58810. this._postProcessManager._rebuild();
  58811. }
  58812. };
  58813. /**
  58814. * Clear the info related to rendering groups preventing retention point in material dispose.
  58815. */
  58816. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  58817. if (this._renderingManager) {
  58818. this._renderingManager.freeRenderingGroups();
  58819. }
  58820. };
  58821. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  58822. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  58823. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  58824. return RenderTargetTexture;
  58825. }(BABYLON.Texture));
  58826. BABYLON.RenderTargetTexture = RenderTargetTexture;
  58827. })(BABYLON || (BABYLON = {}));
  58828. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  58829. "use strict";
  58830. var BABYLON;
  58831. (function (BABYLON) {
  58832. ;
  58833. var MultiRenderTarget = /** @class */ (function (_super) {
  58834. __extends(MultiRenderTarget, _super);
  58835. function MultiRenderTarget(name, size, count, scene, options) {
  58836. var _this = this;
  58837. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  58838. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  58839. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  58840. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  58841. _this._engine = scene.getEngine();
  58842. if (!_this.isSupported) {
  58843. _this.dispose();
  58844. return;
  58845. }
  58846. var types = [];
  58847. var samplingModes = [];
  58848. for (var i = 0; i < count; i++) {
  58849. if (options && options.types && options.types[i] !== undefined) {
  58850. types.push(options.types[i]);
  58851. }
  58852. else {
  58853. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  58854. }
  58855. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  58856. samplingModes.push(options.samplingModes[i]);
  58857. }
  58858. else {
  58859. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58860. }
  58861. }
  58862. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  58863. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  58864. _this._size = size;
  58865. _this._multiRenderTargetOptions = {
  58866. samplingModes: samplingModes,
  58867. generateMipMaps: generateMipMaps,
  58868. generateDepthBuffer: generateDepthBuffer,
  58869. generateStencilBuffer: generateStencilBuffer,
  58870. generateDepthTexture: generateDepthTexture,
  58871. types: types,
  58872. textureCount: count
  58873. };
  58874. _this._createInternalTextures();
  58875. _this._createTextures();
  58876. return _this;
  58877. }
  58878. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  58879. get: function () {
  58880. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  58881. },
  58882. enumerable: true,
  58883. configurable: true
  58884. });
  58885. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  58886. get: function () {
  58887. return this._textures;
  58888. },
  58889. enumerable: true,
  58890. configurable: true
  58891. });
  58892. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  58893. get: function () {
  58894. return this._textures[this._textures.length - 1];
  58895. },
  58896. enumerable: true,
  58897. configurable: true
  58898. });
  58899. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  58900. set: function (wrap) {
  58901. if (this._textures) {
  58902. for (var i = 0; i < this._textures.length; i++) {
  58903. this._textures[i].wrapU = wrap;
  58904. }
  58905. }
  58906. },
  58907. enumerable: true,
  58908. configurable: true
  58909. });
  58910. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  58911. set: function (wrap) {
  58912. if (this._textures) {
  58913. for (var i = 0; i < this._textures.length; i++) {
  58914. this._textures[i].wrapV = wrap;
  58915. }
  58916. }
  58917. },
  58918. enumerable: true,
  58919. configurable: true
  58920. });
  58921. MultiRenderTarget.prototype._rebuild = function () {
  58922. this.releaseInternalTextures();
  58923. this._createInternalTextures();
  58924. for (var i = 0; i < this._internalTextures.length; i++) {
  58925. var texture = this._textures[i];
  58926. texture._texture = this._internalTextures[i];
  58927. }
  58928. // Keeps references to frame buffer and stencil/depth buffer
  58929. this._texture = this._internalTextures[0];
  58930. };
  58931. MultiRenderTarget.prototype._createInternalTextures = function () {
  58932. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  58933. };
  58934. MultiRenderTarget.prototype._createTextures = function () {
  58935. this._textures = [];
  58936. for (var i = 0; i < this._internalTextures.length; i++) {
  58937. var texture = new BABYLON.Texture(null, this.getScene());
  58938. texture._texture = this._internalTextures[i];
  58939. this._textures.push(texture);
  58940. }
  58941. // Keeps references to frame buffer and stencil/depth buffer
  58942. this._texture = this._internalTextures[0];
  58943. };
  58944. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  58945. get: function () {
  58946. return this._samples;
  58947. },
  58948. set: function (value) {
  58949. if (this._samples === value) {
  58950. return;
  58951. }
  58952. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  58953. },
  58954. enumerable: true,
  58955. configurable: true
  58956. });
  58957. MultiRenderTarget.prototype.resize = function (size) {
  58958. this.releaseInternalTextures();
  58959. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  58960. this._createInternalTextures();
  58961. };
  58962. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  58963. var _this = this;
  58964. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  58965. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  58966. });
  58967. };
  58968. MultiRenderTarget.prototype.dispose = function () {
  58969. this.releaseInternalTextures();
  58970. _super.prototype.dispose.call(this);
  58971. };
  58972. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  58973. if (!this._internalTextures) {
  58974. return;
  58975. }
  58976. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  58977. if (this._internalTextures[i] !== undefined) {
  58978. this._internalTextures[i].dispose();
  58979. this._internalTextures.splice(i, 1);
  58980. }
  58981. }
  58982. };
  58983. return MultiRenderTarget;
  58984. }(BABYLON.RenderTargetTexture));
  58985. BABYLON.MultiRenderTarget = MultiRenderTarget;
  58986. })(BABYLON || (BABYLON = {}));
  58987. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  58988. "use strict";
  58989. var BABYLON;
  58990. (function (BABYLON) {
  58991. var MirrorTexture = /** @class */ (function (_super) {
  58992. __extends(MirrorTexture, _super);
  58993. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  58994. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58995. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  58996. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58997. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  58998. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  58999. _this._transformMatrix = BABYLON.Matrix.Zero();
  59000. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  59001. _this._adaptiveBlurKernel = 0;
  59002. _this._blurKernelX = 0;
  59003. _this._blurKernelY = 0;
  59004. _this._blurRatio = 1.0;
  59005. _this.ignoreCameraViewport = true;
  59006. _this.onBeforeRenderObservable.add(function () {
  59007. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  59008. _this._savedViewMatrix = scene.getViewMatrix();
  59009. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  59010. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  59011. scene.clipPlane = _this.mirrorPlane;
  59012. scene.getEngine().cullBackFaces = false;
  59013. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  59014. });
  59015. _this.onAfterRenderObservable.add(function () {
  59016. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  59017. scene.getEngine().cullBackFaces = true;
  59018. scene._mirroredCameraPosition = null;
  59019. delete scene.clipPlane;
  59020. });
  59021. return _this;
  59022. }
  59023. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  59024. get: function () {
  59025. return this._blurRatio;
  59026. },
  59027. set: function (value) {
  59028. if (this._blurRatio === value) {
  59029. return;
  59030. }
  59031. this._blurRatio = value;
  59032. this._preparePostProcesses();
  59033. },
  59034. enumerable: true,
  59035. configurable: true
  59036. });
  59037. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  59038. set: function (value) {
  59039. this._adaptiveBlurKernel = value;
  59040. this._autoComputeBlurKernel();
  59041. },
  59042. enumerable: true,
  59043. configurable: true
  59044. });
  59045. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  59046. set: function (value) {
  59047. this.blurKernelX = value;
  59048. this.blurKernelY = value;
  59049. },
  59050. enumerable: true,
  59051. configurable: true
  59052. });
  59053. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  59054. get: function () {
  59055. return this._blurKernelX;
  59056. },
  59057. set: function (value) {
  59058. if (this._blurKernelX === value) {
  59059. return;
  59060. }
  59061. this._blurKernelX = value;
  59062. this._preparePostProcesses();
  59063. },
  59064. enumerable: true,
  59065. configurable: true
  59066. });
  59067. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  59068. get: function () {
  59069. return this._blurKernelY;
  59070. },
  59071. set: function (value) {
  59072. if (this._blurKernelY === value) {
  59073. return;
  59074. }
  59075. this._blurKernelY = value;
  59076. this._preparePostProcesses();
  59077. },
  59078. enumerable: true,
  59079. configurable: true
  59080. });
  59081. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  59082. var engine = this.getScene().getEngine();
  59083. var dw = this.getRenderWidth() / engine.getRenderWidth();
  59084. var dh = this.getRenderHeight() / engine.getRenderHeight();
  59085. this.blurKernelX = this._adaptiveBlurKernel * dw;
  59086. this.blurKernelY = this._adaptiveBlurKernel * dh;
  59087. };
  59088. MirrorTexture.prototype._onRatioRescale = function () {
  59089. if (this._sizeRatio) {
  59090. this.resize(this._initialSizeParameter);
  59091. if (!this._adaptiveBlurKernel) {
  59092. this._preparePostProcesses();
  59093. }
  59094. }
  59095. if (this._adaptiveBlurKernel) {
  59096. this._autoComputeBlurKernel();
  59097. }
  59098. };
  59099. MirrorTexture.prototype._preparePostProcesses = function () {
  59100. this.clearPostProcesses(true);
  59101. if (this._blurKernelX && this._blurKernelY) {
  59102. var engine = this.getScene().getEngine();
  59103. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59104. 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);
  59105. this._blurX.autoClear = false;
  59106. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  59107. this._blurX.inputTexture = this._texture;
  59108. }
  59109. else {
  59110. this._blurX.alwaysForcePOT = true;
  59111. }
  59112. 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);
  59113. this._blurY.autoClear = false;
  59114. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  59115. this.addPostProcess(this._blurX);
  59116. this.addPostProcess(this._blurY);
  59117. }
  59118. else {
  59119. if (this._blurY) {
  59120. this.removePostProcess(this._blurY);
  59121. this._blurY.dispose();
  59122. this._blurY = null;
  59123. }
  59124. if (this._blurX) {
  59125. this.removePostProcess(this._blurX);
  59126. this._blurX.dispose();
  59127. this._blurX = null;
  59128. }
  59129. }
  59130. };
  59131. MirrorTexture.prototype.clone = function () {
  59132. var scene = this.getScene();
  59133. if (!scene) {
  59134. return this;
  59135. }
  59136. var textureSize = this.getSize();
  59137. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  59138. // Base texture
  59139. newTexture.hasAlpha = this.hasAlpha;
  59140. newTexture.level = this.level;
  59141. // Mirror Texture
  59142. newTexture.mirrorPlane = this.mirrorPlane.clone();
  59143. if (this.renderList) {
  59144. newTexture.renderList = this.renderList.slice(0);
  59145. }
  59146. return newTexture;
  59147. };
  59148. MirrorTexture.prototype.serialize = function () {
  59149. if (!this.name) {
  59150. return null;
  59151. }
  59152. var serializationObject = _super.prototype.serialize.call(this);
  59153. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  59154. return serializationObject;
  59155. };
  59156. return MirrorTexture;
  59157. }(BABYLON.RenderTargetTexture));
  59158. BABYLON.MirrorTexture = MirrorTexture;
  59159. })(BABYLON || (BABYLON = {}));
  59160. //# sourceMappingURL=babylon.mirrorTexture.js.map
  59161. "use strict";
  59162. var BABYLON;
  59163. (function (BABYLON) {
  59164. /**
  59165. * Creates a refraction texture used by refraction channel of the standard material.
  59166. * @param name the texture name
  59167. * @param size size of the underlying texture
  59168. * @param scene root scene
  59169. */
  59170. var RefractionTexture = /** @class */ (function (_super) {
  59171. __extends(RefractionTexture, _super);
  59172. function RefractionTexture(name, size, scene, generateMipMaps) {
  59173. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  59174. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  59175. _this.depth = 2.0;
  59176. _this.onBeforeRenderObservable.add(function () {
  59177. scene.clipPlane = _this.refractionPlane;
  59178. });
  59179. _this.onAfterRenderObservable.add(function () {
  59180. delete scene.clipPlane;
  59181. });
  59182. return _this;
  59183. }
  59184. RefractionTexture.prototype.clone = function () {
  59185. var scene = this.getScene();
  59186. if (!scene) {
  59187. return this;
  59188. }
  59189. var textureSize = this.getSize();
  59190. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  59191. // Base texture
  59192. newTexture.hasAlpha = this.hasAlpha;
  59193. newTexture.level = this.level;
  59194. // Refraction Texture
  59195. newTexture.refractionPlane = this.refractionPlane.clone();
  59196. if (this.renderList) {
  59197. newTexture.renderList = this.renderList.slice(0);
  59198. }
  59199. newTexture.depth = this.depth;
  59200. return newTexture;
  59201. };
  59202. RefractionTexture.prototype.serialize = function () {
  59203. if (!this.name) {
  59204. return null;
  59205. }
  59206. var serializationObject = _super.prototype.serialize.call(this);
  59207. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  59208. serializationObject.depth = this.depth;
  59209. return serializationObject;
  59210. };
  59211. return RefractionTexture;
  59212. }(BABYLON.RenderTargetTexture));
  59213. BABYLON.RefractionTexture = RefractionTexture;
  59214. })(BABYLON || (BABYLON = {}));
  59215. //# sourceMappingURL=babylon.refractionTexture.js.map
  59216. "use strict";
  59217. var BABYLON;
  59218. (function (BABYLON) {
  59219. var DynamicTexture = /** @class */ (function (_super) {
  59220. __extends(DynamicTexture, _super);
  59221. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  59222. if (scene === void 0) { scene = null; }
  59223. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59224. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  59225. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  59226. _this.name = name;
  59227. _this._engine = _this.getScene().getEngine();
  59228. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59229. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59230. _this._generateMipMaps = generateMipMaps;
  59231. if (options.getContext) {
  59232. _this._canvas = options;
  59233. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59234. }
  59235. else {
  59236. _this._canvas = document.createElement("canvas");
  59237. if (options.width) {
  59238. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59239. }
  59240. else {
  59241. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  59242. }
  59243. }
  59244. var textureSize = _this.getSize();
  59245. _this._canvas.width = textureSize.width;
  59246. _this._canvas.height = textureSize.height;
  59247. _this._context = _this._canvas.getContext("2d");
  59248. return _this;
  59249. }
  59250. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  59251. get: function () {
  59252. return true;
  59253. },
  59254. enumerable: true,
  59255. configurable: true
  59256. });
  59257. DynamicTexture.prototype._recreate = function (textureSize) {
  59258. this._canvas.width = textureSize.width;
  59259. this._canvas.height = textureSize.height;
  59260. this.releaseInternalTexture();
  59261. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  59262. };
  59263. DynamicTexture.prototype.scale = function (ratio) {
  59264. var textureSize = this.getSize();
  59265. textureSize.width *= ratio;
  59266. textureSize.height *= ratio;
  59267. this._recreate(textureSize);
  59268. };
  59269. DynamicTexture.prototype.scaleTo = function (width, height) {
  59270. var textureSize = this.getSize();
  59271. textureSize.width = width;
  59272. textureSize.height = height;
  59273. this._recreate(textureSize);
  59274. };
  59275. DynamicTexture.prototype.getContext = function () {
  59276. return this._context;
  59277. };
  59278. DynamicTexture.prototype.clear = function () {
  59279. var size = this.getSize();
  59280. this._context.fillRect(0, 0, size.width, size.height);
  59281. };
  59282. DynamicTexture.prototype.update = function (invertY) {
  59283. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  59284. };
  59285. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  59286. if (update === void 0) { update = true; }
  59287. var size = this.getSize();
  59288. if (clearColor) {
  59289. this._context.fillStyle = clearColor;
  59290. this._context.fillRect(0, 0, size.width, size.height);
  59291. }
  59292. this._context.font = font;
  59293. if (x === null || x === undefined) {
  59294. var textSize = this._context.measureText(text);
  59295. x = (size.width - textSize.width) / 2;
  59296. }
  59297. if (y === null || y === undefined) {
  59298. var fontSize = parseInt((font.replace(/\D/g, '')));
  59299. ;
  59300. y = (size.height / 2) + (fontSize / 3.65);
  59301. }
  59302. this._context.fillStyle = color;
  59303. this._context.fillText(text, x, y);
  59304. if (update) {
  59305. this.update(invertY);
  59306. }
  59307. };
  59308. DynamicTexture.prototype.clone = function () {
  59309. var scene = this.getScene();
  59310. if (!scene) {
  59311. return this;
  59312. }
  59313. var textureSize = this.getSize();
  59314. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  59315. // Base texture
  59316. newTexture.hasAlpha = this.hasAlpha;
  59317. newTexture.level = this.level;
  59318. // Dynamic Texture
  59319. newTexture.wrapU = this.wrapU;
  59320. newTexture.wrapV = this.wrapV;
  59321. return newTexture;
  59322. };
  59323. DynamicTexture.prototype._rebuild = function () {
  59324. this.update();
  59325. };
  59326. return DynamicTexture;
  59327. }(BABYLON.Texture));
  59328. BABYLON.DynamicTexture = DynamicTexture;
  59329. })(BABYLON || (BABYLON = {}));
  59330. //# sourceMappingURL=babylon.dynamicTexture.js.map
  59331. "use strict";
  59332. var BABYLON;
  59333. (function (BABYLON) {
  59334. var VideoTexture = /** @class */ (function (_super) {
  59335. __extends(VideoTexture, _super);
  59336. /**
  59337. * Creates a video texture.
  59338. * Sample : https://doc.babylonjs.com/how_to/video_texture
  59339. * @param {string | null} name optional name, will detect from video source, if not defined
  59340. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  59341. * @param {BABYLON.Scene} scene is obviously the current scene.
  59342. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  59343. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  59344. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  59345. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  59346. */
  59347. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  59348. if (generateMipMaps === void 0) { generateMipMaps = false; }
  59349. if (invertY === void 0) { invertY = false; }
  59350. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59351. if (settings === void 0) { settings = {
  59352. autoPlay: true,
  59353. loop: true,
  59354. autoUpdateTexture: true,
  59355. }; }
  59356. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  59357. _this._createInternalTexture = function () {
  59358. if (_this._texture != null) {
  59359. return;
  59360. }
  59361. if (!_this._engine.needPOTTextures ||
  59362. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  59363. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59364. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59365. }
  59366. else {
  59367. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59368. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59369. _this._generateMipMaps = false;
  59370. }
  59371. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  59372. _this._texture.isReady = true;
  59373. _this._updateInternalTexture();
  59374. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  59375. _this.onLoadObservable.notifyObservers(_this);
  59376. }
  59377. };
  59378. _this.reset = function () {
  59379. if (_this._texture == null) {
  59380. return;
  59381. }
  59382. _this._texture.dispose();
  59383. _this._texture = null;
  59384. };
  59385. _this._updateInternalTexture = function (e) {
  59386. if (_this._texture == null || !_this._texture.isReady) {
  59387. return;
  59388. }
  59389. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  59390. return;
  59391. }
  59392. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  59393. };
  59394. _this._engine = _this.getScene().getEngine();
  59395. _this._generateMipMaps = generateMipMaps;
  59396. _this._samplingMode = samplingMode;
  59397. _this.autoUpdateTexture = settings.autoUpdateTexture;
  59398. _this.name = name || _this._getName(src);
  59399. _this.video = _this._getVideo(src);
  59400. if (settings.autoPlay !== undefined) {
  59401. _this.video.autoplay = settings.autoPlay;
  59402. }
  59403. if (settings.loop !== undefined) {
  59404. _this.video.loop = settings.loop;
  59405. }
  59406. _this.video.addEventListener("canplay", _this._createInternalTexture);
  59407. _this.video.addEventListener("paused", _this._updateInternalTexture);
  59408. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  59409. _this.video.addEventListener("emptied", _this.reset);
  59410. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  59411. _this._createInternalTexture();
  59412. }
  59413. return _this;
  59414. }
  59415. VideoTexture.prototype._getName = function (src) {
  59416. if (src instanceof HTMLVideoElement) {
  59417. return src.currentSrc;
  59418. }
  59419. if (typeof src === "object") {
  59420. return src.toString();
  59421. }
  59422. return src;
  59423. };
  59424. ;
  59425. VideoTexture.prototype._getVideo = function (src) {
  59426. if (src instanceof HTMLVideoElement) {
  59427. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  59428. return src;
  59429. }
  59430. var video = document.createElement("video");
  59431. if (typeof src === "string") {
  59432. BABYLON.Tools.SetCorsBehavior(src, video);
  59433. video.src = src;
  59434. }
  59435. else {
  59436. BABYLON.Tools.SetCorsBehavior(src[0], video);
  59437. src.forEach(function (url) {
  59438. var source = document.createElement("source");
  59439. source.src = url;
  59440. video.appendChild(source);
  59441. });
  59442. }
  59443. return video;
  59444. };
  59445. ;
  59446. /**
  59447. * Internal method to initiate `update`.
  59448. */
  59449. VideoTexture.prototype._rebuild = function () {
  59450. this.update();
  59451. };
  59452. /**
  59453. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  59454. */
  59455. VideoTexture.prototype.update = function () {
  59456. if (!this.autoUpdateTexture) {
  59457. // Expecting user to call `updateTexture` manually
  59458. return;
  59459. }
  59460. this.updateTexture(true);
  59461. };
  59462. /**
  59463. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  59464. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  59465. */
  59466. VideoTexture.prototype.updateTexture = function (isVisible) {
  59467. if (!isVisible) {
  59468. return;
  59469. }
  59470. if (this.video.paused) {
  59471. return;
  59472. }
  59473. this._updateInternalTexture();
  59474. };
  59475. /**
  59476. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  59477. * @param url New url.
  59478. */
  59479. VideoTexture.prototype.updateURL = function (url) {
  59480. this.video.src = url;
  59481. };
  59482. VideoTexture.prototype.dispose = function () {
  59483. _super.prototype.dispose.call(this);
  59484. this.video.removeEventListener("canplay", this._createInternalTexture);
  59485. this.video.removeEventListener("paused", this._updateInternalTexture);
  59486. this.video.removeEventListener("seeked", this._updateInternalTexture);
  59487. this.video.removeEventListener("emptied", this.reset);
  59488. this.video.pause();
  59489. };
  59490. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  59491. var video = document.createElement("video");
  59492. var constraintsDeviceId;
  59493. if (constraints && constraints.deviceId) {
  59494. constraintsDeviceId = {
  59495. exact: constraints.deviceId,
  59496. };
  59497. }
  59498. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  59499. if (navigator.mediaDevices) {
  59500. navigator.mediaDevices.getUserMedia({ video: constraints })
  59501. .then(function (stream) {
  59502. if (video.mozSrcObject !== undefined) {
  59503. // hack for Firefox < 19
  59504. video.mozSrcObject = stream;
  59505. }
  59506. else {
  59507. video.srcObject = stream;
  59508. }
  59509. var onPlaying = function () {
  59510. if (onReady) {
  59511. onReady(new VideoTexture("video", video, scene, true, true));
  59512. }
  59513. video.removeEventListener("playing", onPlaying);
  59514. };
  59515. video.addEventListener("playing", onPlaying);
  59516. video.play();
  59517. })
  59518. .catch(function (err) {
  59519. BABYLON.Tools.Error(err.name);
  59520. });
  59521. }
  59522. else {
  59523. navigator.getUserMedia =
  59524. navigator.getUserMedia ||
  59525. navigator.webkitGetUserMedia ||
  59526. navigator.mozGetUserMedia ||
  59527. navigator.msGetUserMedia;
  59528. if (navigator.getUserMedia) {
  59529. navigator.getUserMedia({
  59530. video: {
  59531. deviceId: constraintsDeviceId,
  59532. width: {
  59533. min: (constraints && constraints.minWidth) || 256,
  59534. max: (constraints && constraints.maxWidth) || 640,
  59535. },
  59536. height: {
  59537. min: (constraints && constraints.minHeight) || 256,
  59538. max: (constraints && constraints.maxHeight) || 480,
  59539. },
  59540. },
  59541. }, function (stream) {
  59542. if (video.mozSrcObject !== undefined) {
  59543. // hack for Firefox < 19
  59544. video.mozSrcObject = stream;
  59545. }
  59546. else {
  59547. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  59548. }
  59549. video.play();
  59550. if (onReady) {
  59551. onReady(new VideoTexture("video", video, scene, true, true));
  59552. }
  59553. }, function (e) {
  59554. BABYLON.Tools.Error(e.name);
  59555. });
  59556. }
  59557. }
  59558. };
  59559. return VideoTexture;
  59560. }(BABYLON.Texture));
  59561. BABYLON.VideoTexture = VideoTexture;
  59562. })(BABYLON || (BABYLON = {}));
  59563. //# sourceMappingURL=babylon.videoTexture.js.map
  59564. "use strict";
  59565. var BABYLON;
  59566. (function (BABYLON) {
  59567. var RawTexture = /** @class */ (function (_super) {
  59568. __extends(RawTexture, _super);
  59569. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  59570. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59571. if (invertY === void 0) { invertY = false; }
  59572. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59573. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59574. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  59575. _this.format = format;
  59576. _this._engine = scene.getEngine();
  59577. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  59578. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59579. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59580. return _this;
  59581. }
  59582. RawTexture.prototype.update = function (data) {
  59583. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  59584. };
  59585. // Statics
  59586. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59587. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59588. if (invertY === void 0) { invertY = false; }
  59589. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59590. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  59591. };
  59592. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59593. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59594. if (invertY === void 0) { invertY = false; }
  59595. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59596. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  59597. };
  59598. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59599. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59600. if (invertY === void 0) { invertY = false; }
  59601. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59602. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  59603. };
  59604. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  59605. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59606. if (invertY === void 0) { invertY = false; }
  59607. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59608. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59609. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  59610. };
  59611. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  59612. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59613. if (invertY === void 0) { invertY = false; }
  59614. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59615. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59616. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  59617. };
  59618. return RawTexture;
  59619. }(BABYLON.Texture));
  59620. BABYLON.RawTexture = RawTexture;
  59621. })(BABYLON || (BABYLON = {}));
  59622. //# sourceMappingURL=babylon.rawTexture.js.map
  59623. "use strict";
  59624. var BABYLON;
  59625. (function (BABYLON) {
  59626. /**
  59627. * PostProcess can be used to apply a shader to a texture after it has been rendered
  59628. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  59629. */
  59630. var PostProcess = /** @class */ (function () {
  59631. /**
  59632. * Creates a new instance of @see PostProcess
  59633. * @param name The name of the PostProcess.
  59634. * @param fragmentUrl The url of the fragment shader to be used.
  59635. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  59636. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  59637. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  59638. * @param camera The camera to apply the render pass to.
  59639. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  59640. * @param engine The engine which the post process will be applied. (default: current engine)
  59641. * @param reusable If the post process can be reused on the same frame. (default: false)
  59642. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  59643. * @param textureType Type of textures used when performing the post process. (default: 0)
  59644. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  59645. * @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
  59646. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  59647. */
  59648. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  59649. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  59650. if (defines === void 0) { defines = null; }
  59651. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59652. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  59653. if (blockCompilation === void 0) { blockCompilation = false; }
  59654. this.name = name;
  59655. /**
  59656. * Width of the texture to apply the post process on
  59657. */
  59658. this.width = -1;
  59659. /**
  59660. * Height of the texture to apply the post process on
  59661. */
  59662. this.height = -1;
  59663. /**
  59664. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  59665. */
  59666. this._outputTexture = null;
  59667. /**
  59668. * If the buffer needs to be cleared before applying the post process. (default: true)
  59669. * Should be set to false if shader will overwrite all previous pixels.
  59670. */
  59671. this.autoClear = true;
  59672. /**
  59673. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  59674. */
  59675. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  59676. /**
  59677. * Animations to be used for the post processing
  59678. */
  59679. this.animations = new Array();
  59680. /**
  59681. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  59682. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  59683. */
  59684. this.enablePixelPerfectMode = false;
  59685. /**
  59686. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  59687. */
  59688. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  59689. /**
  59690. * Force textures to be a power of two (default: false)
  59691. */
  59692. this.alwaysForcePOT = false;
  59693. /**
  59694. * Number of sample textures (default: 1)
  59695. */
  59696. this.samples = 1;
  59697. /**
  59698. * Modify the scale of the post process to be the same as the viewport (default: false)
  59699. */
  59700. this.adaptScaleToCurrentViewport = false;
  59701. this._reusable = false;
  59702. /**
  59703. * Smart array of input and output textures for the post process.
  59704. */
  59705. this._textures = new BABYLON.SmartArray(2);
  59706. /**
  59707. * The index in _textures that corresponds to the output texture.
  59708. */
  59709. this._currentRenderTextureInd = 0;
  59710. this._scaleRatio = new BABYLON.Vector2(1, 1);
  59711. this._texelSize = BABYLON.Vector2.Zero();
  59712. // Events
  59713. /**
  59714. * An event triggered when the postprocess is activated.
  59715. * @type {BABYLON.Observable}
  59716. */
  59717. this.onActivateObservable = new BABYLON.Observable();
  59718. /**
  59719. * An event triggered when the postprocess changes its size.
  59720. * @type {BABYLON.Observable}
  59721. */
  59722. this.onSizeChangedObservable = new BABYLON.Observable();
  59723. /**
  59724. * An event triggered when the postprocess applies its effect.
  59725. * @type {BABYLON.Observable}
  59726. */
  59727. this.onApplyObservable = new BABYLON.Observable();
  59728. /**
  59729. * An event triggered before rendering the postprocess
  59730. * @type {BABYLON.Observable}
  59731. */
  59732. this.onBeforeRenderObservable = new BABYLON.Observable();
  59733. /**
  59734. * An event triggered after rendering the postprocess
  59735. * @type {BABYLON.Observable}
  59736. */
  59737. this.onAfterRenderObservable = new BABYLON.Observable();
  59738. if (camera != null) {
  59739. this._camera = camera;
  59740. this._scene = camera.getScene();
  59741. camera.attachPostProcess(this);
  59742. this._engine = this._scene.getEngine();
  59743. this._scene.postProcesses.push(this);
  59744. }
  59745. else if (engine) {
  59746. this._engine = engine;
  59747. this._engine.postProcesses.push(this);
  59748. }
  59749. this._options = options;
  59750. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  59751. this._reusable = reusable || false;
  59752. this._textureType = textureType;
  59753. this._samplers = samplers || [];
  59754. this._samplers.push("textureSampler");
  59755. this._fragmentUrl = fragmentUrl;
  59756. this._vertexUrl = vertexUrl;
  59757. this._parameters = parameters || [];
  59758. this._parameters.push("scale");
  59759. this._indexParameters = indexParameters;
  59760. if (!blockCompilation) {
  59761. this.updateEffect(defines);
  59762. }
  59763. }
  59764. Object.defineProperty(PostProcess.prototype, "onActivate", {
  59765. /**
  59766. * A function that is added to the onActivateObservable
  59767. */
  59768. set: function (callback) {
  59769. if (this._onActivateObserver) {
  59770. this.onActivateObservable.remove(this._onActivateObserver);
  59771. }
  59772. if (callback) {
  59773. this._onActivateObserver = this.onActivateObservable.add(callback);
  59774. }
  59775. },
  59776. enumerable: true,
  59777. configurable: true
  59778. });
  59779. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  59780. /**
  59781. * A function that is added to the onSizeChangedObservable
  59782. */
  59783. set: function (callback) {
  59784. if (this._onSizeChangedObserver) {
  59785. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  59786. }
  59787. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  59788. },
  59789. enumerable: true,
  59790. configurable: true
  59791. });
  59792. Object.defineProperty(PostProcess.prototype, "onApply", {
  59793. /**
  59794. * A function that is added to the onApplyObservable
  59795. */
  59796. set: function (callback) {
  59797. if (this._onApplyObserver) {
  59798. this.onApplyObservable.remove(this._onApplyObserver);
  59799. }
  59800. this._onApplyObserver = this.onApplyObservable.add(callback);
  59801. },
  59802. enumerable: true,
  59803. configurable: true
  59804. });
  59805. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  59806. /**
  59807. * A function that is added to the onBeforeRenderObservable
  59808. */
  59809. set: function (callback) {
  59810. if (this._onBeforeRenderObserver) {
  59811. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  59812. }
  59813. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  59814. },
  59815. enumerable: true,
  59816. configurable: true
  59817. });
  59818. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  59819. /**
  59820. * A function that is added to the onAfterRenderObservable
  59821. */
  59822. set: function (callback) {
  59823. if (this._onAfterRenderObserver) {
  59824. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  59825. }
  59826. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  59827. },
  59828. enumerable: true,
  59829. configurable: true
  59830. });
  59831. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  59832. /**
  59833. * 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
  59834. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  59835. */
  59836. get: function () {
  59837. return this._textures.data[this._currentRenderTextureInd];
  59838. },
  59839. set: function (value) {
  59840. this._forcedOutputTexture = value;
  59841. },
  59842. enumerable: true,
  59843. configurable: true
  59844. });
  59845. /**
  59846. * Gets the camera which post process is applied to.
  59847. * @returns The camera the post process is applied to.
  59848. */
  59849. PostProcess.prototype.getCamera = function () {
  59850. return this._camera;
  59851. };
  59852. Object.defineProperty(PostProcess.prototype, "texelSize", {
  59853. /**
  59854. * Gets the texel size of the postprocess.
  59855. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  59856. */
  59857. get: function () {
  59858. if (this._shareOutputWithPostProcess) {
  59859. return this._shareOutputWithPostProcess.texelSize;
  59860. }
  59861. if (this._forcedOutputTexture) {
  59862. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  59863. }
  59864. return this._texelSize;
  59865. },
  59866. enumerable: true,
  59867. configurable: true
  59868. });
  59869. /**
  59870. * Gets the engine which this post process belongs to.
  59871. * @returns The engine the post process was enabled with.
  59872. */
  59873. PostProcess.prototype.getEngine = function () {
  59874. return this._engine;
  59875. };
  59876. /**
  59877. * The effect that is created when initializing the post process.
  59878. * @returns The created effect corrisponding the the postprocess.
  59879. */
  59880. PostProcess.prototype.getEffect = function () {
  59881. return this._effect;
  59882. };
  59883. /**
  59884. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  59885. * @param postProcess The post process to share the output with.
  59886. * @returns This post process.
  59887. */
  59888. PostProcess.prototype.shareOutputWith = function (postProcess) {
  59889. this._disposeTextures();
  59890. this._shareOutputWithPostProcess = postProcess;
  59891. return this;
  59892. };
  59893. /**
  59894. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  59895. * This should be called if the post process that shares output with this post process is disabled/disposed.
  59896. */
  59897. PostProcess.prototype.useOwnOutput = function () {
  59898. if (this._textures.length == 0) {
  59899. this._textures = new BABYLON.SmartArray(2);
  59900. }
  59901. this._shareOutputWithPostProcess = null;
  59902. };
  59903. /**
  59904. * Updates the effect with the current post process compile time values and recompiles the shader.
  59905. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  59906. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  59907. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  59908. * @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
  59909. * @param onCompiled Called when the shader has been compiled.
  59910. * @param onError Called if there is an error when compiling a shader.
  59911. */
  59912. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  59913. if (defines === void 0) { defines = null; }
  59914. if (uniforms === void 0) { uniforms = null; }
  59915. if (samplers === void 0) { samplers = null; }
  59916. 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);
  59917. };
  59918. /**
  59919. * The post process is reusable if it can be used multiple times within one frame.
  59920. * @returns If the post process is reusable
  59921. */
  59922. PostProcess.prototype.isReusable = function () {
  59923. return this._reusable;
  59924. };
  59925. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  59926. PostProcess.prototype.markTextureDirty = function () {
  59927. this.width = -1;
  59928. };
  59929. /**
  59930. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  59931. * 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.
  59932. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  59933. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  59934. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  59935. * @returns The target texture that was bound to be written to.
  59936. */
  59937. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  59938. var _this = this;
  59939. if (sourceTexture === void 0) { sourceTexture = null; }
  59940. camera = camera || this._camera;
  59941. var scene = camera.getScene();
  59942. var engine = scene.getEngine();
  59943. var maxSize = engine.getCaps().maxTextureSize;
  59944. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  59945. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  59946. // If rendering to a webvr camera's left or right eye only half the width should be used to avoid resize when rendered to screen
  59947. var webVRCamera = camera.parent;
  59948. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  59949. requiredWidth /= 2;
  59950. }
  59951. var desiredWidth = (this._options.width || requiredWidth);
  59952. var desiredHeight = this._options.height || requiredHeight;
  59953. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  59954. if (this.adaptScaleToCurrentViewport) {
  59955. var currentViewport = engine.currentViewport;
  59956. if (currentViewport) {
  59957. desiredWidth *= currentViewport.width;
  59958. desiredHeight *= currentViewport.height;
  59959. }
  59960. }
  59961. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  59962. if (!this._options.width) {
  59963. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  59964. }
  59965. if (!this._options.height) {
  59966. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  59967. }
  59968. }
  59969. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  59970. if (this._textures.length > 0) {
  59971. for (var i = 0; i < this._textures.length; i++) {
  59972. this._engine._releaseTexture(this._textures.data[i]);
  59973. }
  59974. this._textures.reset();
  59975. }
  59976. this.width = desiredWidth;
  59977. this.height = desiredHeight;
  59978. var textureSize = { width: this.width, height: this.height };
  59979. var textureOptions = {
  59980. generateMipMaps: false,
  59981. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  59982. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  59983. samplingMode: this.renderTargetSamplingMode,
  59984. type: this._textureType
  59985. };
  59986. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59987. if (this._reusable) {
  59988. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59989. }
  59990. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  59991. this.onSizeChangedObservable.notifyObservers(this);
  59992. }
  59993. this._textures.forEach(function (texture) {
  59994. if (texture.samples !== _this.samples) {
  59995. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  59996. }
  59997. });
  59998. }
  59999. var target;
  60000. if (this._shareOutputWithPostProcess) {
  60001. target = this._shareOutputWithPostProcess.inputTexture;
  60002. }
  60003. else if (this._forcedOutputTexture) {
  60004. target = this._forcedOutputTexture;
  60005. this.width = this._forcedOutputTexture.width;
  60006. this.height = this._forcedOutputTexture.height;
  60007. }
  60008. else {
  60009. target = this.inputTexture;
  60010. }
  60011. // Bind the input of this post process to be used as the output of the previous post process.
  60012. if (this.enablePixelPerfectMode) {
  60013. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  60014. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  60015. }
  60016. else {
  60017. this._scaleRatio.copyFromFloats(1, 1);
  60018. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  60019. }
  60020. this.onActivateObservable.notifyObservers(camera);
  60021. // Clear
  60022. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  60023. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  60024. }
  60025. if (this._reusable) {
  60026. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  60027. }
  60028. return target;
  60029. };
  60030. Object.defineProperty(PostProcess.prototype, "isSupported", {
  60031. /**
  60032. * If the post process is supported.
  60033. */
  60034. get: function () {
  60035. return this._effect.isSupported;
  60036. },
  60037. enumerable: true,
  60038. configurable: true
  60039. });
  60040. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  60041. /**
  60042. * The aspect ratio of the output texture.
  60043. */
  60044. get: function () {
  60045. if (this._shareOutputWithPostProcess) {
  60046. return this._shareOutputWithPostProcess.aspectRatio;
  60047. }
  60048. if (this._forcedOutputTexture) {
  60049. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  60050. }
  60051. return this.width / this.height;
  60052. },
  60053. enumerable: true,
  60054. configurable: true
  60055. });
  60056. /**
  60057. * Get a value indicating if the post-process is ready to be used
  60058. * @returns true if the post-process is ready (shader is compiled)
  60059. */
  60060. PostProcess.prototype.isReady = function () {
  60061. return this._effect && this._effect.isReady();
  60062. };
  60063. /**
  60064. * Binds all textures and uniforms to the shader, this will be run on every pass.
  60065. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  60066. */
  60067. PostProcess.prototype.apply = function () {
  60068. // Check
  60069. if (!this._effect || !this._effect.isReady())
  60070. return null;
  60071. // States
  60072. this._engine.enableEffect(this._effect);
  60073. this._engine.setState(false);
  60074. this._engine.setDepthBuffer(false);
  60075. this._engine.setDepthWrite(false);
  60076. // Alpha
  60077. this._engine.setAlphaMode(this.alphaMode);
  60078. if (this.alphaConstants) {
  60079. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  60080. }
  60081. // Bind the output texture of the preivous post process as the input to this post process.
  60082. var source;
  60083. if (this._shareOutputWithPostProcess) {
  60084. source = this._shareOutputWithPostProcess.inputTexture;
  60085. }
  60086. else if (this._forcedOutputTexture) {
  60087. source = this._forcedOutputTexture;
  60088. }
  60089. else {
  60090. source = this.inputTexture;
  60091. }
  60092. this._effect._bindTexture("textureSampler", source);
  60093. // Parameters
  60094. this._effect.setVector2("scale", this._scaleRatio);
  60095. this.onApplyObservable.notifyObservers(this._effect);
  60096. return this._effect;
  60097. };
  60098. PostProcess.prototype._disposeTextures = function () {
  60099. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  60100. return;
  60101. }
  60102. if (this._textures.length > 0) {
  60103. for (var i = 0; i < this._textures.length; i++) {
  60104. this._engine._releaseTexture(this._textures.data[i]);
  60105. }
  60106. }
  60107. this._textures.dispose();
  60108. };
  60109. /**
  60110. * Disposes the post process.
  60111. * @param camera The camera to dispose the post process on.
  60112. */
  60113. PostProcess.prototype.dispose = function (camera) {
  60114. camera = camera || this._camera;
  60115. this._disposeTextures();
  60116. if (this._scene) {
  60117. var index_1 = this._scene.postProcesses.indexOf(this);
  60118. if (index_1 !== -1) {
  60119. this._scene.postProcesses.splice(index_1, 1);
  60120. }
  60121. }
  60122. else {
  60123. var index_2 = this._engine.postProcesses.indexOf(this);
  60124. if (index_2 !== -1) {
  60125. this._engine.postProcesses.splice(index_2, 1);
  60126. }
  60127. }
  60128. if (!camera) {
  60129. return;
  60130. }
  60131. camera.detachPostProcess(this);
  60132. var index = camera._postProcesses.indexOf(this);
  60133. if (index === 0 && camera._postProcesses.length > 0) {
  60134. var firstPostProcess = this._camera._getFirstPostProcess();
  60135. if (firstPostProcess) {
  60136. firstPostProcess.markTextureDirty();
  60137. }
  60138. }
  60139. this.onActivateObservable.clear();
  60140. this.onAfterRenderObservable.clear();
  60141. this.onApplyObservable.clear();
  60142. this.onBeforeRenderObservable.clear();
  60143. this.onSizeChangedObservable.clear();
  60144. };
  60145. return PostProcess;
  60146. }());
  60147. BABYLON.PostProcess = PostProcess;
  60148. })(BABYLON || (BABYLON = {}));
  60149. //# sourceMappingURL=babylon.postProcess.js.map
  60150. "use strict";
  60151. var BABYLON;
  60152. (function (BABYLON) {
  60153. var PassPostProcess = /** @class */ (function (_super) {
  60154. __extends(PassPostProcess, _super);
  60155. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  60156. if (camera === void 0) { camera = null; }
  60157. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60158. if (blockCompilation === void 0) { blockCompilation = false; }
  60159. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  60160. }
  60161. return PassPostProcess;
  60162. }(BABYLON.PostProcess));
  60163. BABYLON.PassPostProcess = PassPostProcess;
  60164. })(BABYLON || (BABYLON = {}));
  60165. //# sourceMappingURL=babylon.passPostProcess.js.map
  60166. "use strict";
  60167. var __assign = (this && this.__assign) || Object.assign || function(t) {
  60168. for (var s, i = 1, n = arguments.length; i < n; i++) {
  60169. s = arguments[i];
  60170. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  60171. t[p] = s[p];
  60172. }
  60173. return t;
  60174. };
  60175. var BABYLON;
  60176. (function (BABYLON) {
  60177. /**
  60178. * Default implementation of @see IShadowGenerator.
  60179. * This is the main object responsible of generating shadows in the framework.
  60180. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  60181. */
  60182. var ShadowGenerator = /** @class */ (function () {
  60183. /**
  60184. * Creates a ShadowGenerator object.
  60185. * A ShadowGenerator is the required tool to use the shadows.
  60186. * Each light casting shadows needs to use its own ShadowGenerator.
  60187. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  60188. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  60189. * @param light The light object generating the shadows.
  60190. * @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.
  60191. */
  60192. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  60193. this._bias = 0.00005;
  60194. this._normalBias = 0;
  60195. this._blurBoxOffset = 1;
  60196. this._blurScale = 2;
  60197. this._blurKernel = 1;
  60198. this._useKernelBlur = false;
  60199. this._filter = ShadowGenerator.FILTER_NONE;
  60200. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  60201. this._contactHardeningLightSizeUVRatio = 0.1;
  60202. this._darkness = 0;
  60203. this._transparencyShadow = false;
  60204. /**
  60205. * Controls the extent to which the shadows fade out at the edge of the frustum
  60206. * Used only by directionals and spots
  60207. */
  60208. this.frustumEdgeFalloff = 0;
  60209. /**
  60210. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  60211. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  60212. * It might on the other hand introduce peter panning.
  60213. */
  60214. this.forceBackFacesOnly = false;
  60215. this._lightDirection = BABYLON.Vector3.Zero();
  60216. this._viewMatrix = BABYLON.Matrix.Zero();
  60217. this._projectionMatrix = BABYLON.Matrix.Zero();
  60218. this._transformMatrix = BABYLON.Matrix.Zero();
  60219. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  60220. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  60221. this._currentFaceIndex = 0;
  60222. this._currentFaceIndexCache = 0;
  60223. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  60224. this._mapSize = mapSize;
  60225. this._light = light;
  60226. this._scene = light.getScene();
  60227. light._shadowGenerator = this;
  60228. // Texture type fallback from float to int if not supported.
  60229. var caps = this._scene.getEngine().getCaps();
  60230. if (!useFullFloatFirst) {
  60231. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  60232. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60233. }
  60234. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60235. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60236. }
  60237. else {
  60238. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60239. }
  60240. }
  60241. else {
  60242. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60243. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60244. }
  60245. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  60246. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60247. }
  60248. else {
  60249. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60250. }
  60251. }
  60252. this._initializeGenerator();
  60253. this._applyFilterValues();
  60254. }
  60255. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  60256. /**
  60257. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  60258. */
  60259. get: function () {
  60260. return this._bias;
  60261. },
  60262. /**
  60263. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  60264. */
  60265. set: function (bias) {
  60266. this._bias = bias;
  60267. },
  60268. enumerable: true,
  60269. configurable: true
  60270. });
  60271. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  60272. /**
  60273. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  60274. */
  60275. get: function () {
  60276. return this._normalBias;
  60277. },
  60278. /**
  60279. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  60280. */
  60281. set: function (normalBias) {
  60282. this._normalBias = normalBias;
  60283. },
  60284. enumerable: true,
  60285. configurable: true
  60286. });
  60287. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  60288. /**
  60289. * Gets the blur box offset: offset applied during the blur pass.
  60290. * Only usefull if useKernelBlur = false
  60291. */
  60292. get: function () {
  60293. return this._blurBoxOffset;
  60294. },
  60295. /**
  60296. * Sets the blur box offset: offset applied during the blur pass.
  60297. * Only usefull if useKernelBlur = false
  60298. */
  60299. set: function (value) {
  60300. if (this._blurBoxOffset === value) {
  60301. return;
  60302. }
  60303. this._blurBoxOffset = value;
  60304. this._disposeBlurPostProcesses();
  60305. },
  60306. enumerable: true,
  60307. configurable: true
  60308. });
  60309. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  60310. /**
  60311. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  60312. * 2 means half of the size.
  60313. */
  60314. get: function () {
  60315. return this._blurScale;
  60316. },
  60317. /**
  60318. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  60319. * 2 means half of the size.
  60320. */
  60321. set: function (value) {
  60322. if (this._blurScale === value) {
  60323. return;
  60324. }
  60325. this._blurScale = value;
  60326. this._disposeBlurPostProcesses();
  60327. },
  60328. enumerable: true,
  60329. configurable: true
  60330. });
  60331. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  60332. /**
  60333. * Gets the blur kernel: kernel size of the blur pass.
  60334. * Only usefull if useKernelBlur = true
  60335. */
  60336. get: function () {
  60337. return this._blurKernel;
  60338. },
  60339. /**
  60340. * Sets the blur kernel: kernel size of the blur pass.
  60341. * Only usefull if useKernelBlur = true
  60342. */
  60343. set: function (value) {
  60344. if (this._blurKernel === value) {
  60345. return;
  60346. }
  60347. this._blurKernel = value;
  60348. this._disposeBlurPostProcesses();
  60349. },
  60350. enumerable: true,
  60351. configurable: true
  60352. });
  60353. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  60354. /**
  60355. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  60356. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  60357. */
  60358. get: function () {
  60359. return this._useKernelBlur;
  60360. },
  60361. /**
  60362. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  60363. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  60364. */
  60365. set: function (value) {
  60366. if (this._useKernelBlur === value) {
  60367. return;
  60368. }
  60369. this._useKernelBlur = value;
  60370. this._disposeBlurPostProcesses();
  60371. },
  60372. enumerable: true,
  60373. configurable: true
  60374. });
  60375. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  60376. /**
  60377. * Gets the depth scale used in ESM mode.
  60378. */
  60379. get: function () {
  60380. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  60381. },
  60382. /**
  60383. * Sets the depth scale used in ESM mode.
  60384. * This can override the scale stored on the light.
  60385. */
  60386. set: function (value) {
  60387. this._depthScale = value;
  60388. },
  60389. enumerable: true,
  60390. configurable: true
  60391. });
  60392. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  60393. /**
  60394. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  60395. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  60396. */
  60397. get: function () {
  60398. return this._filter;
  60399. },
  60400. /**
  60401. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  60402. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  60403. */
  60404. set: function (value) {
  60405. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  60406. if (this._light.needCube()) {
  60407. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  60408. this.useExponentialShadowMap = true;
  60409. return;
  60410. }
  60411. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  60412. this.useCloseExponentialShadowMap = true;
  60413. return;
  60414. }
  60415. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  60416. this.usePoissonSampling = true;
  60417. return;
  60418. }
  60419. }
  60420. // Weblg1 fallback for PCF.
  60421. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  60422. if (this._scene.getEngine().webGLVersion === 1) {
  60423. this.usePoissonSampling = true;
  60424. return;
  60425. }
  60426. }
  60427. if (this._filter === value) {
  60428. return;
  60429. }
  60430. this._filter = value;
  60431. this._disposeBlurPostProcesses();
  60432. this._applyFilterValues();
  60433. this._light._markMeshesAsLightDirty();
  60434. },
  60435. enumerable: true,
  60436. configurable: true
  60437. });
  60438. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  60439. /**
  60440. * Gets if the current filter is set to Poisson Sampling.
  60441. */
  60442. get: function () {
  60443. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  60444. },
  60445. /**
  60446. * Sets the current filter to Poisson Sampling.
  60447. */
  60448. set: function (value) {
  60449. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  60450. return;
  60451. }
  60452. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  60453. },
  60454. enumerable: true,
  60455. configurable: true
  60456. });
  60457. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  60458. /**
  60459. * Gets if the current filter is set to VSM.
  60460. * DEPRECATED. Should use useExponentialShadowMap instead.
  60461. */
  60462. get: function () {
  60463. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  60464. return this.useExponentialShadowMap;
  60465. },
  60466. /**
  60467. * Sets the current filter is to VSM.
  60468. * DEPRECATED. Should use useExponentialShadowMap instead.
  60469. */
  60470. set: function (value) {
  60471. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  60472. this.useExponentialShadowMap = value;
  60473. },
  60474. enumerable: true,
  60475. configurable: true
  60476. });
  60477. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  60478. /**
  60479. * Gets if the current filter is set to blurred VSM.
  60480. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  60481. */
  60482. get: function () {
  60483. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  60484. return this.useBlurExponentialShadowMap;
  60485. },
  60486. /**
  60487. * Sets the current filter is to blurred VSM.
  60488. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  60489. */
  60490. set: function (value) {
  60491. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  60492. this.useBlurExponentialShadowMap = value;
  60493. },
  60494. enumerable: true,
  60495. configurable: true
  60496. });
  60497. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  60498. /**
  60499. * Gets if the current filter is set to ESM.
  60500. */
  60501. get: function () {
  60502. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  60503. },
  60504. /**
  60505. * Sets the current filter is to ESM.
  60506. */
  60507. set: function (value) {
  60508. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  60509. return;
  60510. }
  60511. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60512. },
  60513. enumerable: true,
  60514. configurable: true
  60515. });
  60516. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  60517. /**
  60518. * Gets if the current filter is set to filtered ESM.
  60519. */
  60520. get: function () {
  60521. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  60522. },
  60523. /**
  60524. * Gets if the current filter is set to filtered ESM.
  60525. */
  60526. set: function (value) {
  60527. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  60528. return;
  60529. }
  60530. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60531. },
  60532. enumerable: true,
  60533. configurable: true
  60534. });
  60535. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  60536. /**
  60537. * Gets if the current filter is set to "close ESM" (using the inverse of the
  60538. * exponential to prevent steep falloff artifacts).
  60539. */
  60540. get: function () {
  60541. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  60542. },
  60543. /**
  60544. * Sets the current filter to "close ESM" (using the inverse of the
  60545. * exponential to prevent steep falloff artifacts).
  60546. */
  60547. set: function (value) {
  60548. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  60549. return;
  60550. }
  60551. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60552. },
  60553. enumerable: true,
  60554. configurable: true
  60555. });
  60556. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  60557. /**
  60558. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  60559. * exponential to prevent steep falloff artifacts).
  60560. */
  60561. get: function () {
  60562. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  60563. },
  60564. /**
  60565. * Sets the current filter to filtered "close ESM" (using the inverse of the
  60566. * exponential to prevent steep falloff artifacts).
  60567. */
  60568. set: function (value) {
  60569. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  60570. return;
  60571. }
  60572. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60573. },
  60574. enumerable: true,
  60575. configurable: true
  60576. });
  60577. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  60578. /**
  60579. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  60580. */
  60581. get: function () {
  60582. return this.filter === ShadowGenerator.FILTER_PCF;
  60583. },
  60584. /**
  60585. * Sets the current filter to "PCF" (percentage closer filtering).
  60586. */
  60587. set: function (value) {
  60588. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  60589. return;
  60590. }
  60591. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  60592. },
  60593. enumerable: true,
  60594. configurable: true
  60595. });
  60596. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  60597. /**
  60598. * Gets the PCF or PCSS Quality.
  60599. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  60600. */
  60601. get: function () {
  60602. return this._filteringQuality;
  60603. },
  60604. /**
  60605. * Sets the PCF or PCSS Quality.
  60606. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  60607. */
  60608. set: function (filteringQuality) {
  60609. this._filteringQuality = filteringQuality;
  60610. },
  60611. enumerable: true,
  60612. configurable: true
  60613. });
  60614. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  60615. /**
  60616. * Gets if the current filter is set to "PCSS" (contact hardening).
  60617. */
  60618. get: function () {
  60619. return this.filter === ShadowGenerator.FILTER_PCSS;
  60620. },
  60621. /**
  60622. * Sets the current filter to "PCSS" (contact hardening).
  60623. */
  60624. set: function (value) {
  60625. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  60626. return;
  60627. }
  60628. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  60629. },
  60630. enumerable: true,
  60631. configurable: true
  60632. });
  60633. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  60634. /**
  60635. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  60636. * Using a ratio helps keeping shape stability independently of the map size.
  60637. *
  60638. * It does not account for the light projection as it was having too much
  60639. * instability during the light setup or during light position changes.
  60640. *
  60641. * Only valid if useContactHardeningShadow is true.
  60642. */
  60643. get: function () {
  60644. return this._contactHardeningLightSizeUVRatio;
  60645. },
  60646. /**
  60647. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  60648. * Using a ratio helps keeping shape stability independently of the map size.
  60649. *
  60650. * It does not account for the light projection as it was having too much
  60651. * instability during the light setup or during light position changes.
  60652. *
  60653. * Only valid if useContactHardeningShadow is true.
  60654. */
  60655. set: function (contactHardeningLightSizeUVRatio) {
  60656. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  60657. },
  60658. enumerable: true,
  60659. configurable: true
  60660. });
  60661. /**
  60662. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  60663. * 0 means strongest and 1 would means no shadow.
  60664. * @returns the darkness.
  60665. */
  60666. ShadowGenerator.prototype.getDarkness = function () {
  60667. return this._darkness;
  60668. };
  60669. /**
  60670. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  60671. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  60672. * @returns the shadow generator allowing fluent coding.
  60673. */
  60674. ShadowGenerator.prototype.setDarkness = function (darkness) {
  60675. if (darkness >= 1.0)
  60676. this._darkness = 1.0;
  60677. else if (darkness <= 0.0)
  60678. this._darkness = 0.0;
  60679. else
  60680. this._darkness = darkness;
  60681. return this;
  60682. };
  60683. /**
  60684. * Sets the ability to have transparent shadow (boolean).
  60685. * @param transparent True if transparent else False
  60686. * @returns the shadow generator allowing fluent coding
  60687. */
  60688. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  60689. this._transparencyShadow = transparent;
  60690. return this;
  60691. };
  60692. /**
  60693. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  60694. * @returns The render target texture if present otherwise, null
  60695. */
  60696. ShadowGenerator.prototype.getShadowMap = function () {
  60697. return this._shadowMap;
  60698. };
  60699. /**
  60700. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  60701. * @returns The render target texture if the shadow map is present otherwise, null
  60702. */
  60703. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  60704. if (this._shadowMap2) {
  60705. return this._shadowMap2;
  60706. }
  60707. return this._shadowMap;
  60708. };
  60709. /**
  60710. * Helper function to add a mesh and its descendants to the list of shadow casters.
  60711. * @param mesh Mesh to add
  60712. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  60713. * @returns the Shadow Generator itself
  60714. */
  60715. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  60716. if (includeDescendants === void 0) { includeDescendants = true; }
  60717. if (!this._shadowMap) {
  60718. return this;
  60719. }
  60720. if (!this._shadowMap.renderList) {
  60721. this._shadowMap.renderList = [];
  60722. }
  60723. this._shadowMap.renderList.push(mesh);
  60724. if (includeDescendants) {
  60725. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  60726. }
  60727. return this;
  60728. var _a;
  60729. };
  60730. /**
  60731. * Helper function to remove a mesh and its descendants from the list of shadow casters
  60732. * @param mesh Mesh to remove
  60733. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  60734. * @returns the Shadow Generator itself
  60735. */
  60736. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  60737. if (includeDescendants === void 0) { includeDescendants = true; }
  60738. if (!this._shadowMap || !this._shadowMap.renderList) {
  60739. return this;
  60740. }
  60741. var index = this._shadowMap.renderList.indexOf(mesh);
  60742. if (index !== -1) {
  60743. this._shadowMap.renderList.splice(index, 1);
  60744. }
  60745. if (includeDescendants) {
  60746. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  60747. var child = _a[_i];
  60748. this.removeShadowCaster(child);
  60749. }
  60750. }
  60751. return this;
  60752. };
  60753. /**
  60754. * Returns the associated light object.
  60755. * @returns the light generating the shadow
  60756. */
  60757. ShadowGenerator.prototype.getLight = function () {
  60758. return this._light;
  60759. };
  60760. ShadowGenerator.prototype._initializeGenerator = function () {
  60761. this._light._markMeshesAsLightDirty();
  60762. this._initializeShadowMap();
  60763. };
  60764. ShadowGenerator.prototype._initializeShadowMap = function () {
  60765. var _this = this;
  60766. // Render target
  60767. var engine = this._scene.getEngine();
  60768. if (engine.webGLVersion > 1) {
  60769. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  60770. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  60771. }
  60772. else {
  60773. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  60774. }
  60775. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60776. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60777. this._shadowMap.anisotropicFilteringLevel = 1;
  60778. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60779. this._shadowMap.renderParticles = false;
  60780. this._shadowMap.ignoreCameraViewport = true;
  60781. // Record Face Index before render.
  60782. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  60783. _this._currentFaceIndex = faceIndex;
  60784. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  60785. engine.setColorWrite(false);
  60786. }
  60787. });
  60788. // Custom render function.
  60789. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  60790. // Blur if required afer render.
  60791. this._shadowMap.onAfterUnbindObservable.add(function () {
  60792. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  60793. engine.setColorWrite(true);
  60794. }
  60795. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  60796. return;
  60797. }
  60798. var shadowMap = _this.getShadowMapForRendering();
  60799. if (shadowMap) {
  60800. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  60801. }
  60802. });
  60803. // Clear according to the chosen filter.
  60804. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  60805. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  60806. this._shadowMap.onClearObservable.add(function (engine) {
  60807. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  60808. engine.clear(clearOne, false, true, false);
  60809. }
  60810. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  60811. engine.clear(clearZero, true, true, false);
  60812. }
  60813. else {
  60814. engine.clear(clearOne, true, true, false);
  60815. }
  60816. });
  60817. };
  60818. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  60819. var _this = this;
  60820. var engine = this._scene.getEngine();
  60821. var targetSize = this._mapSize / this.blurScale;
  60822. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  60823. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  60824. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60825. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60826. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60827. }
  60828. if (this.useKernelBlur) {
  60829. 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);
  60830. this._kernelBlurXPostprocess.width = targetSize;
  60831. this._kernelBlurXPostprocess.height = targetSize;
  60832. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  60833. effect.setTexture("textureSampler", _this._shadowMap);
  60834. });
  60835. 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);
  60836. this._kernelBlurXPostprocess.autoClear = false;
  60837. this._kernelBlurYPostprocess.autoClear = false;
  60838. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60839. this._kernelBlurXPostprocess.packedFloat = true;
  60840. this._kernelBlurYPostprocess.packedFloat = true;
  60841. }
  60842. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  60843. }
  60844. else {
  60845. 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);
  60846. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  60847. effect.setFloat2("screenSize", targetSize, targetSize);
  60848. effect.setTexture("textureSampler", _this._shadowMap);
  60849. });
  60850. this._boxBlurPostprocess.autoClear = false;
  60851. this._blurPostProcesses = [this._boxBlurPostprocess];
  60852. }
  60853. };
  60854. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  60855. var index;
  60856. var engine = this._scene.getEngine();
  60857. if (depthOnlySubMeshes.length) {
  60858. engine.setColorWrite(false);
  60859. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  60860. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  60861. }
  60862. engine.setColorWrite(true);
  60863. }
  60864. for (index = 0; index < opaqueSubMeshes.length; index++) {
  60865. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  60866. }
  60867. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  60868. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  60869. }
  60870. if (this._transparencyShadow) {
  60871. for (index = 0; index < transparentSubMeshes.length; index++) {
  60872. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  60873. }
  60874. }
  60875. };
  60876. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  60877. var _this = this;
  60878. var mesh = subMesh.getRenderingMesh();
  60879. var scene = this._scene;
  60880. var engine = scene.getEngine();
  60881. var material = subMesh.getMaterial();
  60882. if (!material) {
  60883. return;
  60884. }
  60885. // Culling
  60886. engine.setState(material.backFaceCulling);
  60887. // Managing instances
  60888. var batch = mesh._getInstancesRenderList(subMesh._id);
  60889. if (batch.mustReturn) {
  60890. return;
  60891. }
  60892. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  60893. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  60894. engine.enableEffect(this._effect);
  60895. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  60896. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  60897. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  60898. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  60899. this._effect.setVector3("lightData", this._cachedDirection);
  60900. }
  60901. else {
  60902. this._effect.setVector3("lightData", this._cachedPosition);
  60903. }
  60904. if (scene.activeCamera) {
  60905. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  60906. }
  60907. // Alpha test
  60908. if (material && material.needAlphaTesting()) {
  60909. var alphaTexture = material.getAlphaTestTexture();
  60910. if (alphaTexture) {
  60911. this._effect.setTexture("diffuseSampler", alphaTexture);
  60912. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  60913. }
  60914. }
  60915. // Bones
  60916. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60917. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  60918. }
  60919. // Morph targets
  60920. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  60921. if (this.forceBackFacesOnly) {
  60922. engine.setState(true, 0, false, true);
  60923. }
  60924. // Draw
  60925. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  60926. if (this.forceBackFacesOnly) {
  60927. engine.setState(true, 0, false, false);
  60928. }
  60929. }
  60930. else {
  60931. // Need to reset refresh rate of the shadowMap
  60932. if (this._shadowMap) {
  60933. this._shadowMap.resetRefreshCounter();
  60934. }
  60935. }
  60936. };
  60937. ShadowGenerator.prototype._applyFilterValues = function () {
  60938. if (!this._shadowMap) {
  60939. return;
  60940. }
  60941. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  60942. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60943. }
  60944. else {
  60945. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60946. }
  60947. };
  60948. /**
  60949. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  60950. * @param onCompiled Callback triggered at the and of the effects compilation
  60951. * @param options Sets of optional options forcing the compilation with different modes
  60952. */
  60953. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  60954. var _this = this;
  60955. var localOptions = __assign({ useInstances: false }, options);
  60956. var shadowMap = this.getShadowMap();
  60957. if (!shadowMap) {
  60958. if (onCompiled) {
  60959. onCompiled(this);
  60960. }
  60961. return;
  60962. }
  60963. var renderList = shadowMap.renderList;
  60964. if (!renderList) {
  60965. if (onCompiled) {
  60966. onCompiled(this);
  60967. }
  60968. return;
  60969. }
  60970. var subMeshes = new Array();
  60971. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  60972. var mesh = renderList_1[_i];
  60973. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  60974. }
  60975. if (subMeshes.length === 0) {
  60976. if (onCompiled) {
  60977. onCompiled(this);
  60978. }
  60979. return;
  60980. }
  60981. var currentIndex = 0;
  60982. var checkReady = function () {
  60983. if (!_this._scene || !_this._scene.getEngine()) {
  60984. return;
  60985. }
  60986. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  60987. currentIndex++;
  60988. if (currentIndex >= subMeshes.length) {
  60989. if (onCompiled) {
  60990. onCompiled(_this);
  60991. }
  60992. return;
  60993. }
  60994. }
  60995. setTimeout(checkReady, 16);
  60996. };
  60997. checkReady();
  60998. };
  60999. /**
  61000. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  61001. * @param options Sets of optional options forcing the compilation with different modes
  61002. * @returns A promise that resolves when the compilation completes
  61003. */
  61004. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  61005. var _this = this;
  61006. return new Promise(function (resolve) {
  61007. _this.forceCompilation(function () {
  61008. resolve();
  61009. }, options);
  61010. });
  61011. };
  61012. /**
  61013. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  61014. * @param subMesh The submesh we want to render in the shadow map
  61015. * @param useInstances Defines wether will draw in the map using instances
  61016. * @returns true if ready otherwise, false
  61017. */
  61018. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  61019. var defines = [];
  61020. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  61021. defines.push("#define FLOAT");
  61022. }
  61023. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  61024. defines.push("#define ESM");
  61025. }
  61026. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  61027. defines.push("#define DEPTHTEXTURE");
  61028. }
  61029. var attribs = [BABYLON.VertexBuffer.PositionKind];
  61030. var mesh = subMesh.getMesh();
  61031. var material = subMesh.getMaterial();
  61032. // Normal bias.
  61033. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  61034. attribs.push(BABYLON.VertexBuffer.NormalKind);
  61035. defines.push("#define NORMAL");
  61036. if (mesh.nonUniformScaling) {
  61037. defines.push("#define NONUNIFORMSCALING");
  61038. }
  61039. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  61040. defines.push("#define DIRECTIONINLIGHTDATA");
  61041. }
  61042. }
  61043. // Alpha test
  61044. if (material && material.needAlphaTesting()) {
  61045. var alphaTexture = material.getAlphaTestTexture();
  61046. if (alphaTexture) {
  61047. defines.push("#define ALPHATEST");
  61048. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61049. attribs.push(BABYLON.VertexBuffer.UVKind);
  61050. defines.push("#define UV1");
  61051. }
  61052. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61053. if (alphaTexture.coordinatesIndex === 1) {
  61054. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61055. defines.push("#define UV2");
  61056. }
  61057. }
  61058. }
  61059. }
  61060. // Bones
  61061. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61062. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61063. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61064. if (mesh.numBoneInfluencers > 4) {
  61065. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61066. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61067. }
  61068. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61069. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  61070. }
  61071. else {
  61072. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61073. }
  61074. // Morph targets
  61075. var manager = mesh.morphTargetManager;
  61076. var morphInfluencers = 0;
  61077. if (manager) {
  61078. if (manager.numInfluencers > 0) {
  61079. defines.push("#define MORPHTARGETS");
  61080. morphInfluencers = manager.numInfluencers;
  61081. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  61082. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  61083. }
  61084. }
  61085. // Instances
  61086. if (useInstances) {
  61087. defines.push("#define INSTANCES");
  61088. attribs.push("world0");
  61089. attribs.push("world1");
  61090. attribs.push("world2");
  61091. attribs.push("world3");
  61092. }
  61093. // Get correct effect
  61094. var join = defines.join("\n");
  61095. if (this._cachedDefines !== join) {
  61096. this._cachedDefines = join;
  61097. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  61098. }
  61099. if (!this._effect.isReady()) {
  61100. return false;
  61101. }
  61102. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  61103. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  61104. this._initializeBlurRTTAndPostProcesses();
  61105. }
  61106. }
  61107. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  61108. return false;
  61109. }
  61110. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  61111. return false;
  61112. }
  61113. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  61114. return false;
  61115. }
  61116. return true;
  61117. };
  61118. /**
  61119. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  61120. * @param defines Defines of the material we want to update
  61121. * @param lightIndex Index of the light in the enabled light list of the material
  61122. */
  61123. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  61124. var scene = this._scene;
  61125. var light = this._light;
  61126. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  61127. return;
  61128. }
  61129. defines["SHADOW" + lightIndex] = true;
  61130. if (this.useContactHardeningShadow) {
  61131. defines["SHADOWPCSS" + lightIndex] = true;
  61132. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  61133. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  61134. }
  61135. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  61136. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  61137. }
  61138. // else default to high.
  61139. }
  61140. if (this.usePercentageCloserFiltering) {
  61141. defines["SHADOWPCF" + lightIndex] = true;
  61142. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  61143. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  61144. }
  61145. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  61146. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  61147. }
  61148. // else default to high.
  61149. }
  61150. else if (this.usePoissonSampling) {
  61151. defines["SHADOWPOISSON" + lightIndex] = true;
  61152. }
  61153. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  61154. defines["SHADOWESM" + lightIndex] = true;
  61155. }
  61156. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  61157. defines["SHADOWCLOSEESM" + lightIndex] = true;
  61158. }
  61159. if (light.needCube()) {
  61160. defines["SHADOWCUBE" + lightIndex] = true;
  61161. }
  61162. };
  61163. /**
  61164. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  61165. * defined in the generator but impacting the effect).
  61166. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  61167. * @param effect The effect we are binfing the information for
  61168. */
  61169. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  61170. var light = this._light;
  61171. var scene = this._scene;
  61172. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  61173. return;
  61174. }
  61175. var camera = scene.activeCamera;
  61176. if (!camera) {
  61177. return;
  61178. }
  61179. var shadowMap = this.getShadowMap();
  61180. if (!shadowMap) {
  61181. return;
  61182. }
  61183. if (!light.needCube()) {
  61184. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  61185. }
  61186. // Only PCF uses depth stencil texture.
  61187. if (this._filter === ShadowGenerator.FILTER_PCF) {
  61188. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61189. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  61190. }
  61191. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  61192. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61193. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  61194. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  61195. }
  61196. else {
  61197. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61198. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  61199. }
  61200. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  61201. };
  61202. /**
  61203. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  61204. * (eq to shadow prjection matrix * light transform matrix)
  61205. * @returns The transform matrix used to create the shadow map
  61206. */
  61207. ShadowGenerator.prototype.getTransformMatrix = function () {
  61208. var scene = this._scene;
  61209. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  61210. return this._transformMatrix;
  61211. }
  61212. this._currentRenderID = scene.getRenderId();
  61213. this._currentFaceIndexCache = this._currentFaceIndex;
  61214. var lightPosition = this._light.position;
  61215. if (this._light.computeTransformedInformation()) {
  61216. lightPosition = this._light.transformedPosition;
  61217. }
  61218. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  61219. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  61220. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  61221. }
  61222. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  61223. this._cachedPosition.copyFrom(lightPosition);
  61224. this._cachedDirection.copyFrom(this._lightDirection);
  61225. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  61226. var shadowMap = this.getShadowMap();
  61227. if (shadowMap) {
  61228. var renderList = shadowMap.renderList;
  61229. if (renderList) {
  61230. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  61231. }
  61232. }
  61233. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  61234. }
  61235. return this._transformMatrix;
  61236. };
  61237. /**
  61238. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  61239. * Cube and 2D textures for instance.
  61240. */
  61241. ShadowGenerator.prototype.recreateShadowMap = function () {
  61242. var shadowMap = this._shadowMap;
  61243. if (!shadowMap) {
  61244. return;
  61245. }
  61246. // Track render list.
  61247. var renderList = shadowMap.renderList;
  61248. // Clean up existing data.
  61249. this._disposeRTTandPostProcesses();
  61250. // Reinitializes.
  61251. this._initializeGenerator();
  61252. // Reaffect the filter to ensure a correct fallback if necessary.
  61253. this.filter = this.filter;
  61254. // Reaffect the filter.
  61255. this._applyFilterValues();
  61256. // Reaffect Render List.
  61257. this._shadowMap.renderList = renderList;
  61258. };
  61259. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  61260. if (this._shadowMap2) {
  61261. this._shadowMap2.dispose();
  61262. this._shadowMap2 = null;
  61263. }
  61264. if (this._boxBlurPostprocess) {
  61265. this._boxBlurPostprocess.dispose();
  61266. this._boxBlurPostprocess = null;
  61267. }
  61268. if (this._kernelBlurXPostprocess) {
  61269. this._kernelBlurXPostprocess.dispose();
  61270. this._kernelBlurXPostprocess = null;
  61271. }
  61272. if (this._kernelBlurYPostprocess) {
  61273. this._kernelBlurYPostprocess.dispose();
  61274. this._kernelBlurYPostprocess = null;
  61275. }
  61276. this._blurPostProcesses = [];
  61277. };
  61278. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  61279. if (this._shadowMap) {
  61280. this._shadowMap.dispose();
  61281. this._shadowMap = null;
  61282. }
  61283. this._disposeBlurPostProcesses();
  61284. };
  61285. /**
  61286. * Disposes the ShadowGenerator.
  61287. * Returns nothing.
  61288. */
  61289. ShadowGenerator.prototype.dispose = function () {
  61290. this._disposeRTTandPostProcesses();
  61291. if (this._light) {
  61292. this._light._shadowGenerator = null;
  61293. this._light._markMeshesAsLightDirty();
  61294. }
  61295. };
  61296. /**
  61297. * Serializes the shadow generator setup to a json object.
  61298. * @returns The serialized JSON object
  61299. */
  61300. ShadowGenerator.prototype.serialize = function () {
  61301. var serializationObject = {};
  61302. var shadowMap = this.getShadowMap();
  61303. if (!shadowMap) {
  61304. return serializationObject;
  61305. }
  61306. serializationObject.lightId = this._light.id;
  61307. serializationObject.mapSize = shadowMap.getRenderSize();
  61308. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  61309. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  61310. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  61311. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  61312. serializationObject.usePoissonSampling = this.usePoissonSampling;
  61313. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  61314. serializationObject.depthScale = this.depthScale;
  61315. serializationObject.darkness = this.getDarkness();
  61316. serializationObject.blurBoxOffset = this.blurBoxOffset;
  61317. serializationObject.blurKernel = this.blurKernel;
  61318. serializationObject.blurScale = this.blurScale;
  61319. serializationObject.useKernelBlur = this.useKernelBlur;
  61320. serializationObject.transparencyShadow = this._transparencyShadow;
  61321. serializationObject.bias = this.bias;
  61322. serializationObject.normalBias = this.normalBias;
  61323. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  61324. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  61325. serializationObject.filteringQuality = this.filteringQuality;
  61326. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  61327. serializationObject.renderList = [];
  61328. if (shadowMap.renderList) {
  61329. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  61330. var mesh = shadowMap.renderList[meshIndex];
  61331. serializationObject.renderList.push(mesh.id);
  61332. }
  61333. }
  61334. return serializationObject;
  61335. };
  61336. /**
  61337. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  61338. * @param parsedShadowGenerator The JSON object to parse
  61339. * @param scene The scene to create the shadow map for
  61340. * @returns The parsed shadow generator
  61341. */
  61342. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  61343. //casting to point light, as light is missing the position attr and typescript complains.
  61344. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  61345. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  61346. var shadowMap = shadowGenerator.getShadowMap();
  61347. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  61348. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  61349. meshes.forEach(function (mesh) {
  61350. if (!shadowMap) {
  61351. return;
  61352. }
  61353. if (!shadowMap.renderList) {
  61354. shadowMap.renderList = [];
  61355. }
  61356. shadowMap.renderList.push(mesh);
  61357. });
  61358. }
  61359. if (parsedShadowGenerator.usePoissonSampling) {
  61360. shadowGenerator.usePoissonSampling = true;
  61361. }
  61362. else if (parsedShadowGenerator.useExponentialShadowMap) {
  61363. shadowGenerator.useExponentialShadowMap = true;
  61364. }
  61365. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  61366. shadowGenerator.useBlurExponentialShadowMap = true;
  61367. }
  61368. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  61369. shadowGenerator.useCloseExponentialShadowMap = true;
  61370. }
  61371. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  61372. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  61373. }
  61374. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  61375. shadowGenerator.usePercentageCloserFiltering = true;
  61376. }
  61377. else if (parsedShadowGenerator.useContactHardeningShadow) {
  61378. shadowGenerator.useContactHardeningShadow = true;
  61379. }
  61380. if (parsedShadowGenerator.filteringQuality) {
  61381. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  61382. }
  61383. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  61384. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  61385. }
  61386. else if (parsedShadowGenerator.useVarianceShadowMap) {
  61387. shadowGenerator.useExponentialShadowMap = true;
  61388. }
  61389. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  61390. shadowGenerator.useBlurExponentialShadowMap = true;
  61391. }
  61392. if (parsedShadowGenerator.depthScale) {
  61393. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  61394. }
  61395. if (parsedShadowGenerator.blurScale) {
  61396. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  61397. }
  61398. if (parsedShadowGenerator.blurBoxOffset) {
  61399. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  61400. }
  61401. if (parsedShadowGenerator.useKernelBlur) {
  61402. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  61403. }
  61404. if (parsedShadowGenerator.blurKernel) {
  61405. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  61406. }
  61407. if (parsedShadowGenerator.bias !== undefined) {
  61408. shadowGenerator.bias = parsedShadowGenerator.bias;
  61409. }
  61410. if (parsedShadowGenerator.normalBias !== undefined) {
  61411. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  61412. }
  61413. if (parsedShadowGenerator.darkness) {
  61414. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  61415. }
  61416. if (parsedShadowGenerator.transparencyShadow) {
  61417. shadowGenerator.setTransparencyShadow(true);
  61418. }
  61419. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  61420. return shadowGenerator;
  61421. };
  61422. /**
  61423. * Shadow generator mode None: no filtering applied.
  61424. */
  61425. ShadowGenerator.FILTER_NONE = 0;
  61426. /**
  61427. * Shadow generator mode ESM: Exponential Shadow Mapping.
  61428. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  61429. */
  61430. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  61431. /**
  61432. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  61433. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  61434. */
  61435. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  61436. /**
  61437. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  61438. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  61439. */
  61440. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  61441. /**
  61442. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  61443. * edge artifacts on steep falloff.
  61444. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  61445. */
  61446. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  61447. /**
  61448. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  61449. * edge artifacts on steep falloff.
  61450. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  61451. */
  61452. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  61453. /**
  61454. * Shadow generator mode PCF: Percentage Closer Filtering
  61455. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  61456. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  61457. */
  61458. ShadowGenerator.FILTER_PCF = 6;
  61459. /**
  61460. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  61461. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  61462. * Contact Hardening
  61463. */
  61464. ShadowGenerator.FILTER_PCSS = 7;
  61465. /**
  61466. * Reserved for PCF and PCSS
  61467. * Highest Quality.
  61468. *
  61469. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  61470. *
  61471. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  61472. */
  61473. ShadowGenerator.QUALITY_HIGH = 0;
  61474. /**
  61475. * Reserved for PCF and PCSS
  61476. * Good tradeoff for quality/perf cross devices
  61477. *
  61478. * Execute PCF on a 3*3 kernel.
  61479. *
  61480. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  61481. */
  61482. ShadowGenerator.QUALITY_MEDIUM = 1;
  61483. /**
  61484. * Reserved for PCF and PCSS
  61485. * The lowest quality but the fastest.
  61486. *
  61487. * Execute PCF on a 1*1 kernel.
  61488. *
  61489. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  61490. */
  61491. ShadowGenerator.QUALITY_LOW = 2;
  61492. return ShadowGenerator;
  61493. }());
  61494. BABYLON.ShadowGenerator = ShadowGenerator;
  61495. })(BABYLON || (BABYLON = {}));
  61496. //# sourceMappingURL=babylon.shadowGenerator.js.map
  61497. "use strict";
  61498. var BABYLON;
  61499. (function (BABYLON) {
  61500. var DefaultLoadingScreen = /** @class */ (function () {
  61501. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  61502. if (_loadingText === void 0) { _loadingText = ""; }
  61503. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  61504. var _this = this;
  61505. this._renderingCanvas = _renderingCanvas;
  61506. this._loadingText = _loadingText;
  61507. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  61508. // Resize
  61509. this._resizeLoadingUI = function () {
  61510. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  61511. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  61512. if (!_this._loadingDiv) {
  61513. return;
  61514. }
  61515. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  61516. _this._loadingDiv.style.left = canvasRect.left + "px";
  61517. _this._loadingDiv.style.top = canvasRect.top + "px";
  61518. _this._loadingDiv.style.width = canvasRect.width + "px";
  61519. _this._loadingDiv.style.height = canvasRect.height + "px";
  61520. };
  61521. }
  61522. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  61523. if (this._loadingDiv) {
  61524. // Do not add a loading screen if there is already one
  61525. return;
  61526. }
  61527. this._loadingDiv = document.createElement("div");
  61528. this._loadingDiv.id = "babylonjsLoadingDiv";
  61529. this._loadingDiv.style.opacity = "0";
  61530. this._loadingDiv.style.transition = "opacity 1.5s ease";
  61531. this._loadingDiv.style.pointerEvents = "none";
  61532. // Loading text
  61533. this._loadingTextDiv = document.createElement("div");
  61534. this._loadingTextDiv.style.position = "absolute";
  61535. this._loadingTextDiv.style.left = "0";
  61536. this._loadingTextDiv.style.top = "50%";
  61537. this._loadingTextDiv.style.marginTop = "80px";
  61538. this._loadingTextDiv.style.width = "100%";
  61539. this._loadingTextDiv.style.height = "20px";
  61540. this._loadingTextDiv.style.fontFamily = "Arial";
  61541. this._loadingTextDiv.style.fontSize = "14px";
  61542. this._loadingTextDiv.style.color = "white";
  61543. this._loadingTextDiv.style.textAlign = "center";
  61544. this._loadingTextDiv.innerHTML = "Loading";
  61545. this._loadingDiv.appendChild(this._loadingTextDiv);
  61546. //set the predefined text
  61547. this._loadingTextDiv.innerHTML = this._loadingText;
  61548. // Generating keyframes
  61549. var style = document.createElement('style');
  61550. style.type = 'text/css';
  61551. 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 }";
  61552. style.innerHTML = keyFrames;
  61553. document.getElementsByTagName('head')[0].appendChild(style);
  61554. // Loading img
  61555. var imgBack = new Image();
  61556. 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";
  61557. imgBack.style.position = "absolute";
  61558. imgBack.style.left = "50%";
  61559. imgBack.style.top = "50%";
  61560. imgBack.style.marginLeft = "-60px";
  61561. imgBack.style.marginTop = "-60px";
  61562. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  61563. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  61564. imgBack.style.transformOrigin = "50% 50%";
  61565. imgBack.style.webkitTransformOrigin = "50% 50%";
  61566. this._loadingDiv.appendChild(imgBack);
  61567. this._resizeLoadingUI();
  61568. window.addEventListener("resize", this._resizeLoadingUI);
  61569. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  61570. document.body.appendChild(this._loadingDiv);
  61571. this._loadingDiv.style.opacity = "1";
  61572. };
  61573. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  61574. var _this = this;
  61575. if (!this._loadingDiv) {
  61576. return;
  61577. }
  61578. var onTransitionEnd = function () {
  61579. if (!_this._loadingDiv) {
  61580. return;
  61581. }
  61582. document.body.removeChild(_this._loadingDiv);
  61583. window.removeEventListener("resize", _this._resizeLoadingUI);
  61584. _this._loadingDiv = null;
  61585. };
  61586. this._loadingDiv.style.opacity = "0";
  61587. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  61588. };
  61589. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  61590. set: function (text) {
  61591. this._loadingText = text;
  61592. if (this._loadingTextDiv) {
  61593. this._loadingTextDiv.innerHTML = this._loadingText;
  61594. }
  61595. },
  61596. enumerable: true,
  61597. configurable: true
  61598. });
  61599. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  61600. get: function () {
  61601. return this._loadingDivBackgroundColor;
  61602. },
  61603. set: function (color) {
  61604. this._loadingDivBackgroundColor = color;
  61605. if (!this._loadingDiv) {
  61606. return;
  61607. }
  61608. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  61609. },
  61610. enumerable: true,
  61611. configurable: true
  61612. });
  61613. return DefaultLoadingScreen;
  61614. }());
  61615. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  61616. })(BABYLON || (BABYLON = {}));
  61617. //# sourceMappingURL=babylon.loadingScreen.js.map
  61618. "use strict";
  61619. var BABYLON;
  61620. (function (BABYLON) {
  61621. var SceneLoaderProgressEvent = /** @class */ (function () {
  61622. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  61623. this.lengthComputable = lengthComputable;
  61624. this.loaded = loaded;
  61625. this.total = total;
  61626. }
  61627. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  61628. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  61629. };
  61630. return SceneLoaderProgressEvent;
  61631. }());
  61632. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  61633. var SceneLoader = /** @class */ (function () {
  61634. function SceneLoader() {
  61635. }
  61636. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  61637. get: function () {
  61638. return 0;
  61639. },
  61640. enumerable: true,
  61641. configurable: true
  61642. });
  61643. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  61644. get: function () {
  61645. return 1;
  61646. },
  61647. enumerable: true,
  61648. configurable: true
  61649. });
  61650. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  61651. get: function () {
  61652. return 2;
  61653. },
  61654. enumerable: true,
  61655. configurable: true
  61656. });
  61657. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  61658. get: function () {
  61659. return 3;
  61660. },
  61661. enumerable: true,
  61662. configurable: true
  61663. });
  61664. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  61665. get: function () {
  61666. return SceneLoader._ForceFullSceneLoadingForIncremental;
  61667. },
  61668. set: function (value) {
  61669. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  61670. },
  61671. enumerable: true,
  61672. configurable: true
  61673. });
  61674. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  61675. get: function () {
  61676. return SceneLoader._ShowLoadingScreen;
  61677. },
  61678. set: function (value) {
  61679. SceneLoader._ShowLoadingScreen = value;
  61680. },
  61681. enumerable: true,
  61682. configurable: true
  61683. });
  61684. Object.defineProperty(SceneLoader, "loggingLevel", {
  61685. get: function () {
  61686. return SceneLoader._loggingLevel;
  61687. },
  61688. set: function (value) {
  61689. SceneLoader._loggingLevel = value;
  61690. },
  61691. enumerable: true,
  61692. configurable: true
  61693. });
  61694. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  61695. get: function () {
  61696. return SceneLoader._CleanBoneMatrixWeights;
  61697. },
  61698. set: function (value) {
  61699. SceneLoader._CleanBoneMatrixWeights = value;
  61700. },
  61701. enumerable: true,
  61702. configurable: true
  61703. });
  61704. SceneLoader._getDefaultPlugin = function () {
  61705. return SceneLoader._registeredPlugins[".babylon"];
  61706. };
  61707. SceneLoader._getPluginForExtension = function (extension) {
  61708. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  61709. if (registeredPlugin) {
  61710. return registeredPlugin;
  61711. }
  61712. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  61713. return SceneLoader._getDefaultPlugin();
  61714. };
  61715. SceneLoader._getPluginForDirectLoad = function (data) {
  61716. for (var extension in SceneLoader._registeredPlugins) {
  61717. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  61718. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  61719. return SceneLoader._registeredPlugins[extension];
  61720. }
  61721. }
  61722. return SceneLoader._getDefaultPlugin();
  61723. };
  61724. SceneLoader._getPluginForFilename = function (sceneFilename) {
  61725. if (sceneFilename.name) {
  61726. sceneFilename = sceneFilename.name;
  61727. }
  61728. var queryStringPosition = sceneFilename.indexOf("?");
  61729. if (queryStringPosition !== -1) {
  61730. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  61731. }
  61732. var dotPosition = sceneFilename.lastIndexOf(".");
  61733. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  61734. return SceneLoader._getPluginForExtension(extension);
  61735. };
  61736. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  61737. SceneLoader._getDirectLoad = function (sceneFilename) {
  61738. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  61739. return sceneFilename.substr(5);
  61740. }
  61741. return null;
  61742. };
  61743. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  61744. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  61745. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  61746. var plugin;
  61747. if (registeredPlugin.plugin.createPlugin) {
  61748. plugin = registeredPlugin.plugin.createPlugin();
  61749. }
  61750. else {
  61751. plugin = registeredPlugin.plugin;
  61752. }
  61753. var useArrayBuffer = registeredPlugin.isBinary;
  61754. var database;
  61755. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  61756. var dataCallback = function (data, responseURL) {
  61757. if (scene.isDisposed) {
  61758. onError("Scene has been disposed");
  61759. return;
  61760. }
  61761. scene.database = database;
  61762. onSuccess(plugin, data, responseURL);
  61763. };
  61764. var request = null;
  61765. var pluginDisposed = false;
  61766. var onDisposeObservable = plugin.onDisposeObservable;
  61767. if (onDisposeObservable) {
  61768. onDisposeObservable.add(function () {
  61769. pluginDisposed = true;
  61770. if (request) {
  61771. request.abort();
  61772. request = null;
  61773. }
  61774. onDispose();
  61775. });
  61776. }
  61777. var manifestChecked = function () {
  61778. if (pluginDisposed) {
  61779. return;
  61780. }
  61781. var url = rootUrl + sceneFilename;
  61782. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  61783. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  61784. } : undefined, database, useArrayBuffer, function (request, exception) {
  61785. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  61786. });
  61787. };
  61788. if (directLoad) {
  61789. dataCallback(directLoad);
  61790. return plugin;
  61791. }
  61792. if (rootUrl.indexOf("file:") === -1) {
  61793. if (scene.getEngine().enableOfflineSupport) {
  61794. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  61795. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  61796. }
  61797. else {
  61798. manifestChecked();
  61799. }
  61800. }
  61801. else {
  61802. var fileOrString = sceneFilename;
  61803. if (fileOrString.name) {
  61804. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  61805. }
  61806. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  61807. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  61808. }
  61809. else {
  61810. onError("Unable to find file named " + sceneFilename);
  61811. }
  61812. }
  61813. return plugin;
  61814. };
  61815. // Public functions
  61816. SceneLoader.GetPluginForExtension = function (extension) {
  61817. return SceneLoader._getPluginForExtension(extension).plugin;
  61818. };
  61819. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  61820. return !!SceneLoader._registeredPlugins[extension];
  61821. };
  61822. SceneLoader.RegisterPlugin = function (plugin) {
  61823. if (typeof plugin.extensions === "string") {
  61824. var extension = plugin.extensions;
  61825. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  61826. plugin: plugin,
  61827. isBinary: false
  61828. };
  61829. }
  61830. else {
  61831. var extensions = plugin.extensions;
  61832. Object.keys(extensions).forEach(function (extension) {
  61833. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  61834. plugin: plugin,
  61835. isBinary: extensions[extension].isBinary
  61836. };
  61837. });
  61838. }
  61839. };
  61840. /**
  61841. * Import meshes into a scene
  61842. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  61843. * @param rootUrl a string that defines the root url for scene and resources
  61844. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61845. * @param scene the instance of BABYLON.Scene to append to
  61846. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  61847. * @param onProgress a callback with a progress event for each file being loaded
  61848. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61849. * @param pluginExtension the extension used to determine the plugin
  61850. * @returns The loaded plugin
  61851. */
  61852. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61853. if (onSuccess === void 0) { onSuccess = null; }
  61854. if (onProgress === void 0) { onProgress = null; }
  61855. if (onError === void 0) { onError = null; }
  61856. if (pluginExtension === void 0) { pluginExtension = null; }
  61857. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61858. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61859. return null;
  61860. }
  61861. var loadingToken = {};
  61862. scene._addPendingData(loadingToken);
  61863. var disposeHandler = function () {
  61864. scene._removePendingData(loadingToken);
  61865. };
  61866. var errorHandler = function (message, exception) {
  61867. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  61868. if (onError) {
  61869. onError(scene, errorMessage, exception);
  61870. }
  61871. else {
  61872. BABYLON.Tools.Error(errorMessage);
  61873. // should the exception be thrown?
  61874. }
  61875. disposeHandler();
  61876. };
  61877. var progressHandler = onProgress ? function (event) {
  61878. try {
  61879. onProgress(event);
  61880. }
  61881. catch (e) {
  61882. errorHandler("Error in onProgress callback", e);
  61883. }
  61884. } : undefined;
  61885. var successHandler = function (meshes, particleSystems, skeletons) {
  61886. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  61887. if (onSuccess) {
  61888. try {
  61889. onSuccess(meshes, particleSystems, skeletons);
  61890. }
  61891. catch (e) {
  61892. errorHandler("Error in onSuccess callback", e);
  61893. }
  61894. }
  61895. scene._removePendingData(loadingToken);
  61896. };
  61897. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61898. if (plugin.rewriteRootURL) {
  61899. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  61900. }
  61901. if (sceneFilename === "") {
  61902. if (sceneFilename === "") {
  61903. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  61904. }
  61905. }
  61906. if (plugin.importMesh) {
  61907. var syncedPlugin = plugin;
  61908. var meshes = new Array();
  61909. var particleSystems = new Array();
  61910. var skeletons = new Array();
  61911. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  61912. return;
  61913. }
  61914. scene.loadingPluginName = plugin.name;
  61915. successHandler(meshes, particleSystems, skeletons);
  61916. }
  61917. else {
  61918. var asyncedPlugin = plugin;
  61919. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  61920. scene.loadingPluginName = plugin.name;
  61921. successHandler(result.meshes, result.particleSystems, result.skeletons);
  61922. }).catch(function (error) {
  61923. errorHandler(error.message, error);
  61924. });
  61925. }
  61926. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61927. };
  61928. /**
  61929. * Import meshes into a scene
  61930. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  61931. * @param rootUrl a string that defines the root url for scene and resources
  61932. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61933. * @param scene the instance of BABYLON.Scene to append to
  61934. * @param onProgress a callback with a progress event for each file being loaded
  61935. * @param pluginExtension the extension used to determine the plugin
  61936. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  61937. */
  61938. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61939. if (onProgress === void 0) { onProgress = null; }
  61940. if (pluginExtension === void 0) { pluginExtension = null; }
  61941. return new Promise(function (resolve, reject) {
  61942. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  61943. resolve({
  61944. meshes: meshes,
  61945. particleSystems: particleSystems,
  61946. skeletons: skeletons
  61947. });
  61948. }, onProgress, function (scene, message, exception) {
  61949. reject(exception || new Error(message));
  61950. });
  61951. });
  61952. };
  61953. /**
  61954. * Load a scene
  61955. * @param rootUrl a string that defines the root url for scene and resources
  61956. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61957. * @param engine is the instance of BABYLON.Engine to use to create the scene
  61958. * @param onSuccess a callback with the scene when import succeeds
  61959. * @param onProgress a callback with a progress event for each file being loaded
  61960. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61961. * @param pluginExtension the extension used to determine the plugin
  61962. * @returns The loaded plugin
  61963. */
  61964. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  61965. if (onSuccess === void 0) { onSuccess = null; }
  61966. if (onProgress === void 0) { onProgress = null; }
  61967. if (onError === void 0) { onError = null; }
  61968. if (pluginExtension === void 0) { pluginExtension = null; }
  61969. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  61970. };
  61971. /**
  61972. * Load a scene
  61973. * @param rootUrl a string that defines the root url for scene and resources
  61974. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61975. * @param engine is the instance of BABYLON.Engine to use to create the scene
  61976. * @param onProgress a callback with a progress event for each file being loaded
  61977. * @param pluginExtension the extension used to determine the plugin
  61978. * @returns The loaded scene
  61979. */
  61980. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  61981. if (onProgress === void 0) { onProgress = null; }
  61982. if (pluginExtension === void 0) { pluginExtension = null; }
  61983. return new Promise(function (resolve, reject) {
  61984. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  61985. resolve(scene);
  61986. }, onProgress, function (scene, message, exception) {
  61987. reject(exception || new Error(message));
  61988. }, pluginExtension);
  61989. });
  61990. };
  61991. /**
  61992. * Append a scene
  61993. * @param rootUrl a string that defines the root url for scene and resources
  61994. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61995. * @param scene is the instance of BABYLON.Scene to append to
  61996. * @param onSuccess a callback with the scene when import succeeds
  61997. * @param onProgress a callback with a progress event for each file being loaded
  61998. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61999. * @param pluginExtension the extension used to determine the plugin
  62000. * @returns The loaded plugin
  62001. */
  62002. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62003. if (onSuccess === void 0) { onSuccess = null; }
  62004. if (onProgress === void 0) { onProgress = null; }
  62005. if (onError === void 0) { onError = null; }
  62006. if (pluginExtension === void 0) { pluginExtension = null; }
  62007. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62008. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62009. return null;
  62010. }
  62011. if (SceneLoader.ShowLoadingScreen) {
  62012. scene.getEngine().displayLoadingUI();
  62013. }
  62014. var loadingToken = {};
  62015. scene._addPendingData(loadingToken);
  62016. var disposeHandler = function () {
  62017. scene._removePendingData(loadingToken);
  62018. scene.getEngine().hideLoadingUI();
  62019. };
  62020. var errorHandler = function (message, exception) {
  62021. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  62022. if (onError) {
  62023. onError(scene, errorMessage, exception);
  62024. }
  62025. else {
  62026. BABYLON.Tools.Error(errorMessage);
  62027. // should the exception be thrown?
  62028. }
  62029. disposeHandler();
  62030. };
  62031. var progressHandler = onProgress ? function (event) {
  62032. try {
  62033. onProgress(event);
  62034. }
  62035. catch (e) {
  62036. errorHandler("Error in onProgress callback", e);
  62037. }
  62038. } : undefined;
  62039. var successHandler = function () {
  62040. if (onSuccess) {
  62041. try {
  62042. onSuccess(scene);
  62043. }
  62044. catch (e) {
  62045. errorHandler("Error in onSuccess callback", e);
  62046. }
  62047. }
  62048. scene._removePendingData(loadingToken);
  62049. };
  62050. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62051. if (sceneFilename === "") {
  62052. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  62053. }
  62054. if (plugin.load) {
  62055. var syncedPlugin = plugin;
  62056. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  62057. return;
  62058. }
  62059. scene.loadingPluginName = plugin.name;
  62060. successHandler();
  62061. }
  62062. else {
  62063. var asyncedPlugin = plugin;
  62064. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  62065. scene.loadingPluginName = plugin.name;
  62066. successHandler();
  62067. }).catch(function (error) {
  62068. errorHandler(error.message, error);
  62069. });
  62070. }
  62071. if (SceneLoader.ShowLoadingScreen) {
  62072. scene.executeWhenReady(function () {
  62073. scene.getEngine().hideLoadingUI();
  62074. });
  62075. }
  62076. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62077. };
  62078. /**
  62079. * Append a scene
  62080. * @param rootUrl a string that defines the root url for scene and resources
  62081. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62082. * @param scene is the instance of BABYLON.Scene to append to
  62083. * @param onProgress a callback with a progress event for each file being loaded
  62084. * @param pluginExtension the extension used to determine the plugin
  62085. * @returns The given scene
  62086. */
  62087. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62088. if (onProgress === void 0) { onProgress = null; }
  62089. if (pluginExtension === void 0) { pluginExtension = null; }
  62090. return new Promise(function (resolve, reject) {
  62091. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  62092. resolve(scene);
  62093. }, onProgress, function (scene, message, exception) {
  62094. reject(exception || new Error(message));
  62095. }, pluginExtension);
  62096. });
  62097. };
  62098. /**
  62099. * Load a scene into an asset container
  62100. * @param rootUrl a string that defines the root url for scene and resources
  62101. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62102. * @param scene is the instance of BABYLON.Scene to append to
  62103. * @param onSuccess a callback with the scene when import succeeds
  62104. * @param onProgress a callback with a progress event for each file being loaded
  62105. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62106. * @param pluginExtension the extension used to determine the plugin
  62107. * @returns The loaded plugin
  62108. */
  62109. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62110. if (onSuccess === void 0) { onSuccess = null; }
  62111. if (onProgress === void 0) { onProgress = null; }
  62112. if (onError === void 0) { onError = null; }
  62113. if (pluginExtension === void 0) { pluginExtension = null; }
  62114. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62115. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62116. return null;
  62117. }
  62118. var loadingToken = {};
  62119. scene._addPendingData(loadingToken);
  62120. var disposeHandler = function () {
  62121. scene._removePendingData(loadingToken);
  62122. };
  62123. var errorHandler = function (message, exception) {
  62124. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  62125. if (onError) {
  62126. onError(scene, errorMessage, exception);
  62127. }
  62128. else {
  62129. BABYLON.Tools.Error(errorMessage);
  62130. // should the exception be thrown?
  62131. }
  62132. disposeHandler();
  62133. };
  62134. var progressHandler = onProgress ? function (event) {
  62135. try {
  62136. onProgress(event);
  62137. }
  62138. catch (e) {
  62139. errorHandler("Error in onProgress callback", e);
  62140. }
  62141. } : undefined;
  62142. var successHandler = function (assets) {
  62143. if (onSuccess) {
  62144. try {
  62145. onSuccess(assets);
  62146. }
  62147. catch (e) {
  62148. errorHandler("Error in onSuccess callback", e);
  62149. }
  62150. }
  62151. scene._removePendingData(loadingToken);
  62152. };
  62153. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62154. if (plugin.loadAssetContainer) {
  62155. var syncedPlugin = plugin;
  62156. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  62157. if (!assetContainer) {
  62158. return;
  62159. }
  62160. scene.loadingPluginName = plugin.name;
  62161. successHandler(assetContainer);
  62162. }
  62163. else if (plugin.loadAssetContainerAsync) {
  62164. var asyncedPlugin = plugin;
  62165. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  62166. scene.loadingPluginName = plugin.name;
  62167. successHandler(assetContainer);
  62168. }).catch(function (error) {
  62169. errorHandler(error.message, error);
  62170. });
  62171. }
  62172. else {
  62173. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  62174. }
  62175. if (SceneLoader.ShowLoadingScreen) {
  62176. scene.executeWhenReady(function () {
  62177. scene.getEngine().hideLoadingUI();
  62178. });
  62179. }
  62180. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62181. };
  62182. /**
  62183. * Load a scene into an asset container
  62184. * @param rootUrl a string that defines the root url for scene and resources
  62185. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62186. * @param scene is the instance of BABYLON.Scene to append to
  62187. * @param onProgress a callback with a progress event for each file being loaded
  62188. * @param pluginExtension the extension used to determine the plugin
  62189. * @returns The loaded asset container
  62190. */
  62191. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62192. if (onProgress === void 0) { onProgress = null; }
  62193. if (pluginExtension === void 0) { pluginExtension = null; }
  62194. return new Promise(function (resolve, reject) {
  62195. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  62196. resolve(assetContainer);
  62197. }, onProgress, function (scene, message, exception) {
  62198. reject(exception || new Error(message));
  62199. }, pluginExtension);
  62200. });
  62201. };
  62202. // Flags
  62203. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  62204. SceneLoader._ShowLoadingScreen = true;
  62205. SceneLoader._CleanBoneMatrixWeights = false;
  62206. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  62207. // Members
  62208. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  62209. SceneLoader._registeredPlugins = {};
  62210. return SceneLoader;
  62211. }());
  62212. BABYLON.SceneLoader = SceneLoader;
  62213. ;
  62214. })(BABYLON || (BABYLON = {}));
  62215. //# sourceMappingURL=babylon.sceneLoader.js.map
  62216. "use strict";
  62217. var BABYLON;
  62218. (function (BABYLON) {
  62219. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  62220. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  62221. var parsedMaterial = parsedData.materials[index];
  62222. if (parsedMaterial.id === id) {
  62223. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  62224. }
  62225. }
  62226. return null;
  62227. };
  62228. var isDescendantOf = function (mesh, names, hierarchyIds) {
  62229. for (var i in names) {
  62230. if (mesh.name === names[i]) {
  62231. hierarchyIds.push(mesh.id);
  62232. return true;
  62233. }
  62234. }
  62235. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  62236. hierarchyIds.push(mesh.id);
  62237. return true;
  62238. }
  62239. return false;
  62240. };
  62241. var logOperation = function (operation, producer) {
  62242. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  62243. };
  62244. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  62245. if (addToScene === void 0) { addToScene = false; }
  62246. var container = new BABYLON.AssetContainer(scene);
  62247. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62248. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62249. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62250. // and avoid problems with multiple concurrent .babylon loads.
  62251. var log = "importScene has failed JSON parse";
  62252. try {
  62253. var parsedData = JSON.parse(data);
  62254. log = "";
  62255. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  62256. var index;
  62257. var cache;
  62258. // Lights
  62259. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  62260. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  62261. var parsedLight = parsedData.lights[index];
  62262. var light = BABYLON.Light.Parse(parsedLight, scene);
  62263. if (light) {
  62264. container.lights.push(light);
  62265. log += (index === 0 ? "\n\tLights:" : "");
  62266. log += "\n\t\t" + light.toString(fullDetails);
  62267. }
  62268. }
  62269. }
  62270. // Animations
  62271. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  62272. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  62273. var parsedAnimation = parsedData.animations[index];
  62274. var animation = BABYLON.Animation.Parse(parsedAnimation);
  62275. scene.animations.push(animation);
  62276. container.animations.push(animation);
  62277. log += (index === 0 ? "\n\tAnimations:" : "");
  62278. log += "\n\t\t" + animation.toString(fullDetails);
  62279. }
  62280. }
  62281. // Materials
  62282. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  62283. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  62284. var parsedMaterial = parsedData.materials[index];
  62285. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  62286. container.materials.push(mat);
  62287. log += (index === 0 ? "\n\tMaterials:" : "");
  62288. log += "\n\t\t" + mat.toString(fullDetails);
  62289. }
  62290. }
  62291. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  62292. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  62293. var parsedMultiMaterial = parsedData.multiMaterials[index];
  62294. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  62295. container.multiMaterials.push(mmat);
  62296. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  62297. log += "\n\t\t" + mmat.toString(fullDetails);
  62298. }
  62299. }
  62300. // Morph targets
  62301. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  62302. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  62303. var managerData = _a[_i];
  62304. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  62305. }
  62306. }
  62307. // Skeletons
  62308. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  62309. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  62310. var parsedSkeleton = parsedData.skeletons[index];
  62311. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  62312. container.skeletons.push(skeleton);
  62313. log += (index === 0 ? "\n\tSkeletons:" : "");
  62314. log += "\n\t\t" + skeleton.toString(fullDetails);
  62315. }
  62316. }
  62317. // Geometries
  62318. var geometries = parsedData.geometries;
  62319. if (geometries !== undefined && geometries !== null) {
  62320. var addedGeometry = new Array();
  62321. // Boxes
  62322. var boxes = geometries.boxes;
  62323. if (boxes !== undefined && boxes !== null) {
  62324. for (index = 0, cache = boxes.length; index < cache; index++) {
  62325. var parsedBox = boxes[index];
  62326. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  62327. }
  62328. }
  62329. // Spheres
  62330. var spheres = geometries.spheres;
  62331. if (spheres !== undefined && spheres !== null) {
  62332. for (index = 0, cache = spheres.length; index < cache; index++) {
  62333. var parsedSphere = spheres[index];
  62334. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  62335. }
  62336. }
  62337. // Cylinders
  62338. var cylinders = geometries.cylinders;
  62339. if (cylinders !== undefined && cylinders !== null) {
  62340. for (index = 0, cache = cylinders.length; index < cache; index++) {
  62341. var parsedCylinder = cylinders[index];
  62342. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  62343. }
  62344. }
  62345. // Toruses
  62346. var toruses = geometries.toruses;
  62347. if (toruses !== undefined && toruses !== null) {
  62348. for (index = 0, cache = toruses.length; index < cache; index++) {
  62349. var parsedTorus = toruses[index];
  62350. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  62351. }
  62352. }
  62353. // Grounds
  62354. var grounds = geometries.grounds;
  62355. if (grounds !== undefined && grounds !== null) {
  62356. for (index = 0, cache = grounds.length; index < cache; index++) {
  62357. var parsedGround = grounds[index];
  62358. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  62359. }
  62360. }
  62361. // Planes
  62362. var planes = geometries.planes;
  62363. if (planes !== undefined && planes !== null) {
  62364. for (index = 0, cache = planes.length; index < cache; index++) {
  62365. var parsedPlane = planes[index];
  62366. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  62367. }
  62368. }
  62369. // TorusKnots
  62370. var torusKnots = geometries.torusKnots;
  62371. if (torusKnots !== undefined && torusKnots !== null) {
  62372. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  62373. var parsedTorusKnot = torusKnots[index];
  62374. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  62375. }
  62376. }
  62377. // VertexData
  62378. var vertexData = geometries.vertexData;
  62379. if (vertexData !== undefined && vertexData !== null) {
  62380. for (index = 0, cache = vertexData.length; index < cache; index++) {
  62381. var parsedVertexData = vertexData[index];
  62382. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  62383. }
  62384. }
  62385. addedGeometry.forEach(function (g) {
  62386. if (g) {
  62387. container.geometries.push(g);
  62388. }
  62389. });
  62390. }
  62391. // Transform nodes
  62392. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  62393. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  62394. var parsedTransformNode = parsedData.transformNodes[index];
  62395. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  62396. container.transformNodes.push(node);
  62397. }
  62398. }
  62399. // Meshes
  62400. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  62401. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  62402. var parsedMesh = parsedData.meshes[index];
  62403. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  62404. container.meshes.push(mesh);
  62405. log += (index === 0 ? "\n\tMeshes:" : "");
  62406. log += "\n\t\t" + mesh.toString(fullDetails);
  62407. }
  62408. }
  62409. // Cameras
  62410. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  62411. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  62412. var parsedCamera = parsedData.cameras[index];
  62413. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  62414. container.cameras.push(camera);
  62415. log += (index === 0 ? "\n\tCameras:" : "");
  62416. log += "\n\t\t" + camera.toString(fullDetails);
  62417. }
  62418. }
  62419. // Browsing all the graph to connect the dots
  62420. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  62421. var camera = scene.cameras[index];
  62422. if (camera._waitingParentId) {
  62423. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  62424. camera._waitingParentId = null;
  62425. }
  62426. }
  62427. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  62428. var light_1 = scene.lights[index];
  62429. if (light_1 && light_1._waitingParentId) {
  62430. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  62431. light_1._waitingParentId = null;
  62432. }
  62433. }
  62434. // Sounds
  62435. // TODO: add sound
  62436. var loadedSounds = [];
  62437. var loadedSound;
  62438. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  62439. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  62440. var parsedSound = parsedData.sounds[index];
  62441. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62442. if (!parsedSound.url)
  62443. parsedSound.url = parsedSound.name;
  62444. if (!loadedSounds[parsedSound.url]) {
  62445. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  62446. loadedSounds[parsedSound.url] = loadedSound;
  62447. container.sounds.push(loadedSound);
  62448. }
  62449. else {
  62450. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  62451. }
  62452. }
  62453. else {
  62454. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  62455. }
  62456. }
  62457. }
  62458. loadedSounds = [];
  62459. // Connect parents & children and parse actions
  62460. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  62461. var transformNode = scene.transformNodes[index];
  62462. if (transformNode._waitingParentId) {
  62463. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  62464. transformNode._waitingParentId = null;
  62465. }
  62466. }
  62467. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62468. var mesh = scene.meshes[index];
  62469. if (mesh._waitingParentId) {
  62470. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  62471. mesh._waitingParentId = null;
  62472. }
  62473. if (mesh._waitingActions) {
  62474. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  62475. mesh._waitingActions = null;
  62476. }
  62477. }
  62478. // freeze world matrix application
  62479. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62480. var currentMesh = scene.meshes[index];
  62481. if (currentMesh._waitingFreezeWorldMatrix) {
  62482. currentMesh.freezeWorldMatrix();
  62483. currentMesh._waitingFreezeWorldMatrix = null;
  62484. }
  62485. else {
  62486. currentMesh.computeWorldMatrix(true);
  62487. }
  62488. }
  62489. // Particles Systems
  62490. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  62491. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  62492. var parsedParticleSystem = parsedData.particleSystems[index];
  62493. if (parsedParticleSystem.activeParticleCount) {
  62494. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62495. container.particleSystems.push(ps);
  62496. }
  62497. else {
  62498. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62499. container.particleSystems.push(ps);
  62500. }
  62501. }
  62502. }
  62503. // Lens flares
  62504. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  62505. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  62506. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  62507. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  62508. container.lensFlareSystems.push(lf);
  62509. }
  62510. }
  62511. // Shadows
  62512. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  62513. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  62514. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  62515. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  62516. container.shadowGenerators.push(sg);
  62517. }
  62518. }
  62519. // Lights exclusions / inclusions
  62520. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  62521. var light_2 = scene.lights[index];
  62522. // Excluded check
  62523. if (light_2._excludedMeshesIds.length > 0) {
  62524. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  62525. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  62526. if (excludedMesh) {
  62527. light_2.excludedMeshes.push(excludedMesh);
  62528. }
  62529. }
  62530. light_2._excludedMeshesIds = [];
  62531. }
  62532. // Included check
  62533. if (light_2._includedOnlyMeshesIds.length > 0) {
  62534. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  62535. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  62536. if (includedOnlyMesh) {
  62537. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  62538. }
  62539. }
  62540. light_2._includedOnlyMeshesIds = [];
  62541. }
  62542. }
  62543. // Actions (scene)
  62544. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  62545. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  62546. }
  62547. if (!addToScene) {
  62548. container.removeAllFromScene();
  62549. }
  62550. }
  62551. catch (err) {
  62552. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  62553. if (onError) {
  62554. onError(msg, err);
  62555. }
  62556. else {
  62557. BABYLON.Tools.Log(msg);
  62558. throw err;
  62559. }
  62560. }
  62561. finally {
  62562. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62563. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62564. }
  62565. }
  62566. return container;
  62567. };
  62568. BABYLON.SceneLoader.RegisterPlugin({
  62569. name: "babylon.js",
  62570. extensions: ".babylon",
  62571. canDirectLoad: function (data) {
  62572. if (data.indexOf("babylon") !== -1) {
  62573. return true;
  62574. }
  62575. return false;
  62576. },
  62577. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  62578. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62579. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62580. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62581. // and avoid problems with multiple concurrent .babylon loads.
  62582. var log = "importMesh has failed JSON parse";
  62583. try {
  62584. var parsedData = JSON.parse(data);
  62585. log = "";
  62586. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  62587. if (!meshesNames) {
  62588. meshesNames = null;
  62589. }
  62590. else if (!Array.isArray(meshesNames)) {
  62591. meshesNames = [meshesNames];
  62592. }
  62593. var hierarchyIds = new Array();
  62594. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  62595. var loadedSkeletonsIds = [];
  62596. var loadedMaterialsIds = [];
  62597. var index;
  62598. var cache;
  62599. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  62600. var parsedMesh = parsedData.meshes[index];
  62601. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  62602. if (meshesNames !== null) {
  62603. // Remove found mesh name from list.
  62604. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  62605. }
  62606. //Geometry?
  62607. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  62608. //does the file contain geometries?
  62609. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  62610. //find the correct geometry and add it to the scene
  62611. var found = false;
  62612. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  62613. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  62614. return;
  62615. }
  62616. else {
  62617. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  62618. if (parsedGeometryData.id === parsedMesh.geometryId) {
  62619. switch (geometryType) {
  62620. case "boxes":
  62621. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  62622. break;
  62623. case "spheres":
  62624. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  62625. break;
  62626. case "cylinders":
  62627. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  62628. break;
  62629. case "toruses":
  62630. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  62631. break;
  62632. case "grounds":
  62633. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  62634. break;
  62635. case "planes":
  62636. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  62637. break;
  62638. case "torusKnots":
  62639. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  62640. break;
  62641. case "vertexData":
  62642. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  62643. break;
  62644. }
  62645. found = true;
  62646. }
  62647. });
  62648. }
  62649. });
  62650. if (found === false) {
  62651. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  62652. }
  62653. }
  62654. }
  62655. // Material ?
  62656. if (parsedMesh.materialId) {
  62657. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  62658. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  62659. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  62660. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  62661. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  62662. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  62663. var subMatId = parsedMultiMaterial.materials[matIndex];
  62664. loadedMaterialsIds.push(subMatId);
  62665. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  62666. if (mat) {
  62667. log += "\n\tMaterial " + mat.toString(fullDetails);
  62668. }
  62669. }
  62670. loadedMaterialsIds.push(parsedMultiMaterial.id);
  62671. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  62672. if (mmat) {
  62673. materialFound = true;
  62674. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  62675. }
  62676. break;
  62677. }
  62678. }
  62679. }
  62680. if (materialFound === false) {
  62681. loadedMaterialsIds.push(parsedMesh.materialId);
  62682. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  62683. if (!mat) {
  62684. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  62685. }
  62686. else {
  62687. log += "\n\tMaterial " + mat.toString(fullDetails);
  62688. }
  62689. }
  62690. }
  62691. // Skeleton ?
  62692. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  62693. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  62694. if (skeletonAlreadyLoaded === false) {
  62695. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  62696. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  62697. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  62698. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  62699. skeletons.push(skeleton);
  62700. loadedSkeletonsIds.push(parsedSkeleton.id);
  62701. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  62702. }
  62703. }
  62704. }
  62705. }
  62706. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  62707. meshes.push(mesh);
  62708. log += "\n\tMesh " + mesh.toString(fullDetails);
  62709. }
  62710. }
  62711. // Connecting parents
  62712. var currentMesh;
  62713. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62714. currentMesh = scene.meshes[index];
  62715. if (currentMesh._waitingParentId) {
  62716. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  62717. currentMesh._waitingParentId = null;
  62718. }
  62719. }
  62720. // freeze and compute world matrix application
  62721. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62722. currentMesh = scene.meshes[index];
  62723. if (currentMesh._waitingFreezeWorldMatrix) {
  62724. currentMesh.freezeWorldMatrix();
  62725. currentMesh._waitingFreezeWorldMatrix = null;
  62726. }
  62727. else {
  62728. currentMesh.computeWorldMatrix(true);
  62729. }
  62730. }
  62731. }
  62732. // Particles
  62733. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  62734. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  62735. var parsedParticleSystem = parsedData.particleSystems[index];
  62736. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  62737. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  62738. }
  62739. }
  62740. }
  62741. return true;
  62742. }
  62743. catch (err) {
  62744. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  62745. if (onError) {
  62746. onError(msg, err);
  62747. }
  62748. else {
  62749. BABYLON.Tools.Log(msg);
  62750. throw err;
  62751. }
  62752. }
  62753. finally {
  62754. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62755. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62756. }
  62757. }
  62758. return false;
  62759. },
  62760. load: function (scene, data, rootUrl, onError) {
  62761. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62762. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62763. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62764. // and avoid problems with multiple concurrent .babylon loads.
  62765. var log = "importScene has failed JSON parse";
  62766. try {
  62767. var parsedData = JSON.parse(data);
  62768. log = "";
  62769. // Scene
  62770. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  62771. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  62772. }
  62773. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  62774. scene.autoClear = parsedData.autoClear;
  62775. }
  62776. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  62777. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  62778. }
  62779. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  62780. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  62781. }
  62782. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  62783. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  62784. }
  62785. // Fog
  62786. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  62787. scene.fogMode = parsedData.fogMode;
  62788. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  62789. scene.fogStart = parsedData.fogStart;
  62790. scene.fogEnd = parsedData.fogEnd;
  62791. scene.fogDensity = parsedData.fogDensity;
  62792. log += "\tFog mode for scene: ";
  62793. switch (scene.fogMode) {
  62794. // getters not compiling, so using hardcoded
  62795. case 1:
  62796. log += "exp\n";
  62797. break;
  62798. case 2:
  62799. log += "exp2\n";
  62800. break;
  62801. case 3:
  62802. log += "linear\n";
  62803. break;
  62804. }
  62805. }
  62806. //Physics
  62807. if (parsedData.physicsEnabled) {
  62808. var physicsPlugin;
  62809. if (parsedData.physicsEngine === "cannon") {
  62810. physicsPlugin = new BABYLON.CannonJSPlugin();
  62811. }
  62812. else if (parsedData.physicsEngine === "oimo") {
  62813. physicsPlugin = new BABYLON.OimoJSPlugin();
  62814. }
  62815. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  62816. //else - default engine, which is currently oimo
  62817. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  62818. scene.enablePhysics(physicsGravity, physicsPlugin);
  62819. }
  62820. // Metadata
  62821. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  62822. scene.metadata = parsedData.metadata;
  62823. }
  62824. //collisions, if defined. otherwise, default is true
  62825. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  62826. scene.collisionsEnabled = parsedData.collisionsEnabled;
  62827. }
  62828. scene.workerCollisions = !!parsedData.workerCollisions;
  62829. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  62830. if (!container) {
  62831. return false;
  62832. }
  62833. if (parsedData.autoAnimate) {
  62834. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  62835. }
  62836. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  62837. scene.setActiveCameraByID(parsedData.activeCameraID);
  62838. }
  62839. // Environment texture
  62840. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  62841. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  62842. if (parsedData.createDefaultSkybox === true) {
  62843. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  62844. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  62845. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  62846. }
  62847. }
  62848. // Finish
  62849. return true;
  62850. }
  62851. catch (err) {
  62852. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  62853. if (onError) {
  62854. onError(msg, err);
  62855. }
  62856. else {
  62857. BABYLON.Tools.Log(msg);
  62858. throw err;
  62859. }
  62860. }
  62861. finally {
  62862. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62863. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62864. }
  62865. }
  62866. return false;
  62867. },
  62868. loadAssetContainer: function (scene, data, rootUrl, onError) {
  62869. var container = loadAssetContainer(scene, data, rootUrl, onError);
  62870. return container;
  62871. }
  62872. });
  62873. })(BABYLON || (BABYLON = {}));
  62874. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  62875. "use strict";
  62876. var BABYLON;
  62877. (function (BABYLON) {
  62878. var FilesInput = /** @class */ (function () {
  62879. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  62880. this.onProcessFileCallback = function () { return true; };
  62881. this._engine = engine;
  62882. this._currentScene = scene;
  62883. this._sceneLoadedCallback = sceneLoadedCallback;
  62884. this._progressCallback = progressCallback;
  62885. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  62886. this._textureLoadingCallback = textureLoadingCallback;
  62887. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  62888. this._onReloadCallback = onReloadCallback;
  62889. this._errorCallback = errorCallback;
  62890. }
  62891. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  62892. var _this = this;
  62893. if (elementToMonitor) {
  62894. this._elementToMonitor = elementToMonitor;
  62895. this._dragEnterHandler = function (e) { _this.drag(e); };
  62896. this._dragOverHandler = function (e) { _this.drag(e); };
  62897. this._dropHandler = function (e) { _this.drop(e); };
  62898. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  62899. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  62900. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  62901. }
  62902. };
  62903. FilesInput.prototype.dispose = function () {
  62904. if (!this._elementToMonitor) {
  62905. return;
  62906. }
  62907. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  62908. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  62909. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  62910. };
  62911. FilesInput.prototype.renderFunction = function () {
  62912. if (this._additionalRenderLoopLogicCallback) {
  62913. this._additionalRenderLoopLogicCallback();
  62914. }
  62915. if (this._currentScene) {
  62916. if (this._textureLoadingCallback) {
  62917. var remaining = this._currentScene.getWaitingItemsCount();
  62918. if (remaining > 0) {
  62919. this._textureLoadingCallback(remaining);
  62920. }
  62921. }
  62922. this._currentScene.render();
  62923. }
  62924. };
  62925. FilesInput.prototype.drag = function (e) {
  62926. e.stopPropagation();
  62927. e.preventDefault();
  62928. };
  62929. FilesInput.prototype.drop = function (eventDrop) {
  62930. eventDrop.stopPropagation();
  62931. eventDrop.preventDefault();
  62932. this.loadFiles(eventDrop);
  62933. };
  62934. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  62935. var _this = this;
  62936. var reader = folder.createReader();
  62937. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  62938. reader.readEntries(function (entries) {
  62939. remaining.count += entries.length;
  62940. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  62941. var entry = entries_1[_i];
  62942. if (entry.isFile) {
  62943. entry.file(function (file) {
  62944. file.correctName = relativePath + file.name;
  62945. files.push(file);
  62946. if (--remaining.count === 0) {
  62947. callback();
  62948. }
  62949. });
  62950. }
  62951. else if (entry.isDirectory) {
  62952. _this._traverseFolder(entry, files, remaining, callback);
  62953. }
  62954. }
  62955. if (--remaining.count) {
  62956. callback();
  62957. }
  62958. });
  62959. };
  62960. FilesInput.prototype._processFiles = function (files) {
  62961. for (var i = 0; i < files.length; i++) {
  62962. var name = files[i].correctName.toLowerCase();
  62963. var extension = name.split('.').pop();
  62964. if (!this.onProcessFileCallback(files[i], name, extension)) {
  62965. continue;
  62966. }
  62967. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  62968. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  62969. this._sceneFileToLoad = files[i];
  62970. }
  62971. else {
  62972. FilesInput.FilesToLoad[name] = files[i];
  62973. }
  62974. }
  62975. };
  62976. FilesInput.prototype.loadFiles = function (event) {
  62977. var _this = this;
  62978. if (this._startingProcessingFilesCallback)
  62979. this._startingProcessingFilesCallback();
  62980. // Handling data transfer via drag'n'drop
  62981. if (event && event.dataTransfer && event.dataTransfer.files) {
  62982. this._filesToLoad = event.dataTransfer.files;
  62983. }
  62984. // Handling files from input files
  62985. if (event && event.target && event.target.files) {
  62986. this._filesToLoad = event.target.files;
  62987. }
  62988. if (this._filesToLoad && this._filesToLoad.length > 0) {
  62989. var files_1 = new Array();
  62990. var folders = [];
  62991. var items = event.dataTransfer ? event.dataTransfer.items : null;
  62992. for (var i = 0; i < this._filesToLoad.length; i++) {
  62993. var fileToLoad = this._filesToLoad[i];
  62994. var name_1 = fileToLoad.name.toLowerCase();
  62995. var entry = void 0;
  62996. fileToLoad.correctName = name_1;
  62997. if (items) {
  62998. var item = items[i];
  62999. if (item.getAsEntry) {
  63000. entry = item.getAsEntry();
  63001. }
  63002. else if (item.webkitGetAsEntry) {
  63003. entry = item.webkitGetAsEntry();
  63004. }
  63005. }
  63006. if (!entry) {
  63007. files_1.push(fileToLoad);
  63008. }
  63009. else {
  63010. if (entry.isDirectory) {
  63011. folders.push(entry);
  63012. }
  63013. else {
  63014. files_1.push(fileToLoad);
  63015. }
  63016. }
  63017. }
  63018. if (folders.length === 0) {
  63019. this._processFiles(files_1);
  63020. this._processReload();
  63021. }
  63022. else {
  63023. var remaining = { count: folders.length };
  63024. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  63025. var folder = folders_1[_i];
  63026. this._traverseFolder(folder, files_1, remaining, function () {
  63027. _this._processFiles(files_1);
  63028. if (remaining.count === 0) {
  63029. _this._processReload();
  63030. }
  63031. });
  63032. }
  63033. }
  63034. }
  63035. };
  63036. FilesInput.prototype._processReload = function () {
  63037. if (this._onReloadCallback) {
  63038. this._onReloadCallback(this._sceneFileToLoad);
  63039. }
  63040. else {
  63041. this.reload();
  63042. }
  63043. };
  63044. FilesInput.prototype.reload = function () {
  63045. var _this = this;
  63046. // If a scene file has been provided
  63047. if (this._sceneFileToLoad) {
  63048. if (this._currentScene) {
  63049. if (BABYLON.Tools.errorsCount > 0) {
  63050. BABYLON.Tools.ClearLogCache();
  63051. }
  63052. this._engine.stopRenderLoop();
  63053. this._currentScene.dispose();
  63054. }
  63055. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  63056. if (_this._progressCallback) {
  63057. _this._progressCallback(progress);
  63058. }
  63059. }).then(function (scene) {
  63060. _this._currentScene = scene;
  63061. if (_this._sceneLoadedCallback) {
  63062. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  63063. }
  63064. // Wait for textures and shaders to be ready
  63065. _this._currentScene.executeWhenReady(function () {
  63066. _this._engine.runRenderLoop(function () {
  63067. _this.renderFunction();
  63068. });
  63069. });
  63070. }).catch(function (error) {
  63071. if (_this._errorCallback) {
  63072. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  63073. }
  63074. });
  63075. }
  63076. else {
  63077. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  63078. }
  63079. };
  63080. FilesInput.FilesToLoad = {};
  63081. return FilesInput;
  63082. }());
  63083. BABYLON.FilesInput = FilesInput;
  63084. })(BABYLON || (BABYLON = {}));
  63085. //# sourceMappingURL=babylon.filesInput.js.map
  63086. "use strict";
  63087. var BABYLON;
  63088. (function (BABYLON) {
  63089. /**
  63090. * This class implement a typical dictionary using a string as key and the generic type T as value.
  63091. * The underlying implementation relies on an associative array to ensure the best performances.
  63092. * The value can be anything including 'null' but except 'undefined'
  63093. */
  63094. var StringDictionary = /** @class */ (function () {
  63095. function StringDictionary() {
  63096. this._count = 0;
  63097. this._data = {};
  63098. }
  63099. /**
  63100. * This will clear this dictionary and copy the content from the 'source' one.
  63101. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  63102. * @param source the dictionary to take the content from and copy to this dictionary
  63103. */
  63104. StringDictionary.prototype.copyFrom = function (source) {
  63105. var _this = this;
  63106. this.clear();
  63107. source.forEach(function (t, v) { return _this.add(t, v); });
  63108. };
  63109. /**
  63110. * Get a value based from its key
  63111. * @param key the given key to get the matching value from
  63112. * @return the value if found, otherwise undefined is returned
  63113. */
  63114. StringDictionary.prototype.get = function (key) {
  63115. var val = this._data[key];
  63116. if (val !== undefined) {
  63117. return val;
  63118. }
  63119. return undefined;
  63120. };
  63121. /**
  63122. * Get a value from its key or add it if it doesn't exist.
  63123. * This method will ensure you that a given key/data will be present in the dictionary.
  63124. * @param key the given key to get the matching value from
  63125. * @param factory the factory that will create the value if the key is not present in the dictionary.
  63126. * The factory will only be invoked if there's no data for the given key.
  63127. * @return the value corresponding to the key.
  63128. */
  63129. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  63130. var val = this.get(key);
  63131. if (val !== undefined) {
  63132. return val;
  63133. }
  63134. val = factory(key);
  63135. if (val) {
  63136. this.add(key, val);
  63137. }
  63138. return val;
  63139. };
  63140. /**
  63141. * Get a value from its key if present in the dictionary otherwise add it
  63142. * @param key the key to get the value from
  63143. * @param val if there's no such key/value pair in the dictionary add it with this value
  63144. * @return the value corresponding to the key
  63145. */
  63146. StringDictionary.prototype.getOrAdd = function (key, val) {
  63147. var curVal = this.get(key);
  63148. if (curVal !== undefined) {
  63149. return curVal;
  63150. }
  63151. this.add(key, val);
  63152. return val;
  63153. };
  63154. /**
  63155. * Check if there's a given key in the dictionary
  63156. * @param key the key to check for
  63157. * @return true if the key is present, false otherwise
  63158. */
  63159. StringDictionary.prototype.contains = function (key) {
  63160. return this._data[key] !== undefined;
  63161. };
  63162. /**
  63163. * Add a new key and its corresponding value
  63164. * @param key the key to add
  63165. * @param value the value corresponding to the key
  63166. * @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
  63167. */
  63168. StringDictionary.prototype.add = function (key, value) {
  63169. if (this._data[key] !== undefined) {
  63170. return false;
  63171. }
  63172. this._data[key] = value;
  63173. ++this._count;
  63174. return true;
  63175. };
  63176. StringDictionary.prototype.set = function (key, value) {
  63177. if (this._data[key] === undefined) {
  63178. return false;
  63179. }
  63180. this._data[key] = value;
  63181. return true;
  63182. };
  63183. /**
  63184. * Get the element of the given key and remove it from the dictionary
  63185. * @param key
  63186. */
  63187. StringDictionary.prototype.getAndRemove = function (key) {
  63188. var val = this.get(key);
  63189. if (val !== undefined) {
  63190. delete this._data[key];
  63191. --this._count;
  63192. return val;
  63193. }
  63194. return null;
  63195. };
  63196. /**
  63197. * Remove a key/value from the dictionary.
  63198. * @param key the key to remove
  63199. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  63200. */
  63201. StringDictionary.prototype.remove = function (key) {
  63202. if (this.contains(key)) {
  63203. delete this._data[key];
  63204. --this._count;
  63205. return true;
  63206. }
  63207. return false;
  63208. };
  63209. /**
  63210. * Clear the whole content of the dictionary
  63211. */
  63212. StringDictionary.prototype.clear = function () {
  63213. this._data = {};
  63214. this._count = 0;
  63215. };
  63216. Object.defineProperty(StringDictionary.prototype, "count", {
  63217. get: function () {
  63218. return this._count;
  63219. },
  63220. enumerable: true,
  63221. configurable: true
  63222. });
  63223. /**
  63224. * Execute a callback on each key/val of the dictionary.
  63225. * Note that you can remove any element in this dictionary in the callback implementation
  63226. * @param callback the callback to execute on a given key/value pair
  63227. */
  63228. StringDictionary.prototype.forEach = function (callback) {
  63229. for (var cur in this._data) {
  63230. var val = this._data[cur];
  63231. callback(cur, val);
  63232. }
  63233. };
  63234. /**
  63235. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  63236. * If the callback returns null or undefined the method will iterate to the next key/value pair
  63237. * Note that you can remove any element in this dictionary in the callback implementation
  63238. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  63239. */
  63240. StringDictionary.prototype.first = function (callback) {
  63241. for (var cur in this._data) {
  63242. var val = this._data[cur];
  63243. var res = callback(cur, val);
  63244. if (res) {
  63245. return res;
  63246. }
  63247. }
  63248. return null;
  63249. };
  63250. return StringDictionary;
  63251. }());
  63252. BABYLON.StringDictionary = StringDictionary;
  63253. })(BABYLON || (BABYLON = {}));
  63254. //# sourceMappingURL=babylon.stringDictionary.js.map
  63255. "use strict";
  63256. var BABYLON;
  63257. (function (BABYLON) {
  63258. var Tags = /** @class */ (function () {
  63259. function Tags() {
  63260. }
  63261. Tags.EnableFor = function (obj) {
  63262. obj._tags = obj._tags || {};
  63263. obj.hasTags = function () {
  63264. return Tags.HasTags(obj);
  63265. };
  63266. obj.addTags = function (tagsString) {
  63267. return Tags.AddTagsTo(obj, tagsString);
  63268. };
  63269. obj.removeTags = function (tagsString) {
  63270. return Tags.RemoveTagsFrom(obj, tagsString);
  63271. };
  63272. obj.matchesTagsQuery = function (tagsQuery) {
  63273. return Tags.MatchesQuery(obj, tagsQuery);
  63274. };
  63275. };
  63276. Tags.DisableFor = function (obj) {
  63277. delete obj._tags;
  63278. delete obj.hasTags;
  63279. delete obj.addTags;
  63280. delete obj.removeTags;
  63281. delete obj.matchesTagsQuery;
  63282. };
  63283. Tags.HasTags = function (obj) {
  63284. if (!obj._tags) {
  63285. return false;
  63286. }
  63287. return !BABYLON.Tools.IsEmpty(obj._tags);
  63288. };
  63289. Tags.GetTags = function (obj, asString) {
  63290. if (asString === void 0) { asString = true; }
  63291. if (!obj._tags) {
  63292. return null;
  63293. }
  63294. if (asString) {
  63295. var tagsArray = [];
  63296. for (var tag in obj._tags) {
  63297. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  63298. tagsArray.push(tag);
  63299. }
  63300. }
  63301. return tagsArray.join(" ");
  63302. }
  63303. else {
  63304. return obj._tags;
  63305. }
  63306. };
  63307. // the tags 'true' and 'false' are reserved and cannot be used as tags
  63308. // a tag cannot start with '||', '&&', and '!'
  63309. // it cannot contain whitespaces
  63310. Tags.AddTagsTo = function (obj, tagsString) {
  63311. if (!tagsString) {
  63312. return;
  63313. }
  63314. if (typeof tagsString !== "string") {
  63315. return;
  63316. }
  63317. var tags = tagsString.split(" ");
  63318. tags.forEach(function (tag, index, array) {
  63319. Tags._AddTagTo(obj, tag);
  63320. });
  63321. };
  63322. Tags._AddTagTo = function (obj, tag) {
  63323. tag = tag.trim();
  63324. if (tag === "" || tag === "true" || tag === "false") {
  63325. return;
  63326. }
  63327. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  63328. return;
  63329. }
  63330. Tags.EnableFor(obj);
  63331. obj._tags[tag] = true;
  63332. };
  63333. Tags.RemoveTagsFrom = function (obj, tagsString) {
  63334. if (!Tags.HasTags(obj)) {
  63335. return;
  63336. }
  63337. var tags = tagsString.split(" ");
  63338. for (var t in tags) {
  63339. Tags._RemoveTagFrom(obj, tags[t]);
  63340. }
  63341. };
  63342. Tags._RemoveTagFrom = function (obj, tag) {
  63343. delete obj._tags[tag];
  63344. };
  63345. Tags.MatchesQuery = function (obj, tagsQuery) {
  63346. if (tagsQuery === undefined) {
  63347. return true;
  63348. }
  63349. if (tagsQuery === "") {
  63350. return Tags.HasTags(obj);
  63351. }
  63352. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  63353. };
  63354. return Tags;
  63355. }());
  63356. BABYLON.Tags = Tags;
  63357. })(BABYLON || (BABYLON = {}));
  63358. //# sourceMappingURL=babylon.tags.js.map
  63359. "use strict";
  63360. var BABYLON;
  63361. (function (BABYLON) {
  63362. var AndOrNotEvaluator = /** @class */ (function () {
  63363. function AndOrNotEvaluator() {
  63364. }
  63365. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  63366. if (!query.match(/\([^\(\)]*\)/g)) {
  63367. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  63368. }
  63369. else {
  63370. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  63371. // remove parenthesis
  63372. r = r.slice(1, r.length - 1);
  63373. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  63374. });
  63375. }
  63376. if (query === "true") {
  63377. return true;
  63378. }
  63379. if (query === "false") {
  63380. return false;
  63381. }
  63382. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  63383. };
  63384. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  63385. evaluateCallback = evaluateCallback || (function (r) {
  63386. return r === "true" ? true : false;
  63387. });
  63388. var result;
  63389. var or = parenthesisContent.split("||");
  63390. for (var i in or) {
  63391. if (or.hasOwnProperty(i)) {
  63392. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  63393. var and = ori.split("&&");
  63394. if (and.length > 1) {
  63395. for (var j = 0; j < and.length; ++j) {
  63396. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  63397. if (andj !== "true" && andj !== "false") {
  63398. if (andj[0] === "!") {
  63399. result = !evaluateCallback(andj.substring(1));
  63400. }
  63401. else {
  63402. result = evaluateCallback(andj);
  63403. }
  63404. }
  63405. else {
  63406. result = andj === "true" ? true : false;
  63407. }
  63408. if (!result) {
  63409. ori = "false";
  63410. break;
  63411. }
  63412. }
  63413. }
  63414. if (result || ori === "true") {
  63415. result = true;
  63416. break;
  63417. }
  63418. // result equals false (or undefined)
  63419. if (ori !== "true" && ori !== "false") {
  63420. if (ori[0] === "!") {
  63421. result = !evaluateCallback(ori.substring(1));
  63422. }
  63423. else {
  63424. result = evaluateCallback(ori);
  63425. }
  63426. }
  63427. else {
  63428. result = ori === "true" ? true : false;
  63429. }
  63430. }
  63431. }
  63432. // the whole parenthesis scope is replaced by 'true' or 'false'
  63433. return result ? "true" : "false";
  63434. };
  63435. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  63436. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  63437. // remove whitespaces
  63438. r = r.replace(/[\s]/g, function () { return ""; });
  63439. return r.length % 2 ? "!" : "";
  63440. });
  63441. booleanString = booleanString.trim();
  63442. if (booleanString === "!true") {
  63443. booleanString = "false";
  63444. }
  63445. else if (booleanString === "!false") {
  63446. booleanString = "true";
  63447. }
  63448. return booleanString;
  63449. };
  63450. return AndOrNotEvaluator;
  63451. }());
  63452. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  63453. })(BABYLON || (BABYLON = {}));
  63454. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  63455. "use strict";
  63456. var BABYLON;
  63457. (function (BABYLON) {
  63458. var Database = /** @class */ (function () {
  63459. function Database(urlToScene, callbackManifestChecked) {
  63460. // Handling various flavors of prefixed version of IndexedDB
  63461. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  63462. this.callbackManifestChecked = callbackManifestChecked;
  63463. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  63464. this.db = null;
  63465. this._enableSceneOffline = false;
  63466. this._enableTexturesOffline = false;
  63467. this.manifestVersionFound = 0;
  63468. this.mustUpdateRessources = false;
  63469. this.hasReachedQuota = false;
  63470. if (!Database.IDBStorageEnabled) {
  63471. this.callbackManifestChecked(true);
  63472. }
  63473. else {
  63474. this.checkManifestFile();
  63475. }
  63476. }
  63477. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  63478. get: function () {
  63479. return this._enableSceneOffline;
  63480. },
  63481. enumerable: true,
  63482. configurable: true
  63483. });
  63484. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  63485. get: function () {
  63486. return this._enableTexturesOffline;
  63487. },
  63488. enumerable: true,
  63489. configurable: true
  63490. });
  63491. Database.prototype.checkManifestFile = function () {
  63492. var _this = this;
  63493. var noManifestFile = function () {
  63494. _this._enableSceneOffline = false;
  63495. _this._enableTexturesOffline = false;
  63496. _this.callbackManifestChecked(false);
  63497. };
  63498. var timeStampUsed = false;
  63499. var manifestURL = this.currentSceneUrl + ".manifest";
  63500. var xhr = new XMLHttpRequest();
  63501. if (navigator.onLine) {
  63502. // Adding a timestamp to by-pass browsers' cache
  63503. timeStampUsed = true;
  63504. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  63505. }
  63506. xhr.open("GET", manifestURL, true);
  63507. xhr.addEventListener("load", function () {
  63508. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  63509. try {
  63510. var manifestFile = JSON.parse(xhr.response);
  63511. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  63512. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  63513. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  63514. _this.manifestVersionFound = manifestFile.version;
  63515. }
  63516. if (_this.callbackManifestChecked) {
  63517. _this.callbackManifestChecked(true);
  63518. }
  63519. }
  63520. catch (ex) {
  63521. noManifestFile();
  63522. }
  63523. }
  63524. else {
  63525. noManifestFile();
  63526. }
  63527. }, false);
  63528. xhr.addEventListener("error", function (event) {
  63529. if (timeStampUsed) {
  63530. timeStampUsed = false;
  63531. // Let's retry without the timeStamp
  63532. // It could fail when coupled with HTML5 Offline API
  63533. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  63534. xhr.open("GET", retryManifestURL, true);
  63535. xhr.send();
  63536. }
  63537. else {
  63538. noManifestFile();
  63539. }
  63540. }, false);
  63541. try {
  63542. xhr.send();
  63543. }
  63544. catch (ex) {
  63545. BABYLON.Tools.Error("Error on XHR send request.");
  63546. this.callbackManifestChecked(false);
  63547. }
  63548. };
  63549. Database.prototype.openAsync = function (successCallback, errorCallback) {
  63550. var _this = this;
  63551. var handleError = function () {
  63552. _this.isSupported = false;
  63553. if (errorCallback)
  63554. errorCallback();
  63555. };
  63556. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  63557. // Your browser doesn't support IndexedDB
  63558. this.isSupported = false;
  63559. if (errorCallback)
  63560. errorCallback();
  63561. }
  63562. else {
  63563. // If the DB hasn't been opened or created yet
  63564. if (!this.db) {
  63565. this.hasReachedQuota = false;
  63566. this.isSupported = true;
  63567. var request = this.idbFactory.open("babylonjs", 1);
  63568. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  63569. request.onerror = function (event) {
  63570. handleError();
  63571. };
  63572. // executes when a version change transaction cannot complete due to other active transactions
  63573. request.onblocked = function (event) {
  63574. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  63575. handleError();
  63576. };
  63577. // DB has been opened successfully
  63578. request.onsuccess = function (event) {
  63579. _this.db = request.result;
  63580. successCallback();
  63581. };
  63582. // Initialization of the DB. Creating Scenes & Textures stores
  63583. request.onupgradeneeded = function (event) {
  63584. _this.db = (event.target).result;
  63585. if (_this.db) {
  63586. try {
  63587. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  63588. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  63589. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  63590. }
  63591. catch (ex) {
  63592. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  63593. handleError();
  63594. }
  63595. }
  63596. };
  63597. }
  63598. else {
  63599. if (successCallback)
  63600. successCallback();
  63601. }
  63602. }
  63603. };
  63604. Database.prototype.loadImageFromDB = function (url, image) {
  63605. var _this = this;
  63606. var completeURL = Database.ReturnFullUrlLocation(url);
  63607. var saveAndLoadImage = function () {
  63608. if (!_this.hasReachedQuota && _this.db !== null) {
  63609. // the texture is not yet in the DB, let's try to save it
  63610. _this._saveImageIntoDBAsync(completeURL, image);
  63611. }
  63612. else {
  63613. image.src = url;
  63614. }
  63615. };
  63616. if (!this.mustUpdateRessources) {
  63617. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  63618. }
  63619. else {
  63620. saveAndLoadImage();
  63621. }
  63622. };
  63623. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  63624. if (this.isSupported && this.db !== null) {
  63625. var texture;
  63626. var transaction = this.db.transaction(["textures"]);
  63627. transaction.onabort = function (event) {
  63628. image.src = url;
  63629. };
  63630. transaction.oncomplete = function (event) {
  63631. var blobTextureURL;
  63632. if (texture) {
  63633. var URL = window.URL || window.webkitURL;
  63634. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  63635. image.onerror = function () {
  63636. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  63637. image.src = url;
  63638. };
  63639. image.src = blobTextureURL;
  63640. }
  63641. else {
  63642. notInDBCallback();
  63643. }
  63644. };
  63645. var getRequest = transaction.objectStore("textures").get(url);
  63646. getRequest.onsuccess = function (event) {
  63647. texture = (event.target).result;
  63648. };
  63649. getRequest.onerror = function (event) {
  63650. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  63651. image.src = url;
  63652. };
  63653. }
  63654. else {
  63655. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63656. image.src = url;
  63657. }
  63658. };
  63659. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  63660. var _this = this;
  63661. if (this.isSupported) {
  63662. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  63663. var generateBlobUrl = function () {
  63664. var blobTextureURL;
  63665. if (blob) {
  63666. var URL = window.URL || window.webkitURL;
  63667. try {
  63668. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  63669. }
  63670. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  63671. catch (ex) {
  63672. blobTextureURL = URL.createObjectURL(blob);
  63673. }
  63674. }
  63675. if (blobTextureURL) {
  63676. image.src = blobTextureURL;
  63677. }
  63678. };
  63679. if (Database.IsUASupportingBlobStorage) {
  63680. var xhr = new XMLHttpRequest(), blob;
  63681. xhr.open("GET", url, true);
  63682. xhr.responseType = "blob";
  63683. xhr.addEventListener("load", function () {
  63684. if (xhr.status === 200 && _this.db) {
  63685. // Blob as response (XHR2)
  63686. blob = xhr.response;
  63687. var transaction = _this.db.transaction(["textures"], "readwrite");
  63688. // the transaction could abort because of a QuotaExceededError error
  63689. transaction.onabort = function (event) {
  63690. try {
  63691. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  63692. var srcElement = (event.srcElement || event.target);
  63693. var error = srcElement.error;
  63694. if (error && error.name === "QuotaExceededError") {
  63695. _this.hasReachedQuota = true;
  63696. }
  63697. }
  63698. catch (ex) { }
  63699. generateBlobUrl();
  63700. };
  63701. transaction.oncomplete = function (event) {
  63702. generateBlobUrl();
  63703. };
  63704. var newTexture = { textureUrl: url, data: blob };
  63705. try {
  63706. // Put the blob into the dabase
  63707. var addRequest = transaction.objectStore("textures").put(newTexture);
  63708. addRequest.onsuccess = function (event) {
  63709. };
  63710. addRequest.onerror = function (event) {
  63711. generateBlobUrl();
  63712. };
  63713. }
  63714. catch (ex) {
  63715. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  63716. if (ex.code === 25) {
  63717. Database.IsUASupportingBlobStorage = false;
  63718. }
  63719. image.src = url;
  63720. }
  63721. }
  63722. else {
  63723. image.src = url;
  63724. }
  63725. }, false);
  63726. xhr.addEventListener("error", function (event) {
  63727. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  63728. image.src = url;
  63729. }, false);
  63730. xhr.send();
  63731. }
  63732. else {
  63733. image.src = url;
  63734. }
  63735. }
  63736. else {
  63737. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63738. image.src = url;
  63739. }
  63740. };
  63741. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  63742. var _this = this;
  63743. var updateVersion = function () {
  63744. // the version is not yet in the DB or we need to update it
  63745. _this._saveVersionIntoDBAsync(url, versionLoaded);
  63746. };
  63747. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  63748. };
  63749. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  63750. var _this = this;
  63751. if (this.isSupported && this.db) {
  63752. var version;
  63753. try {
  63754. var transaction = this.db.transaction(["versions"]);
  63755. transaction.oncomplete = function (event) {
  63756. if (version) {
  63757. // If the version in the JSON file is > than the version in DB
  63758. if (_this.manifestVersionFound > version.data) {
  63759. _this.mustUpdateRessources = true;
  63760. updateInDBCallback();
  63761. }
  63762. else {
  63763. callback(version.data);
  63764. }
  63765. }
  63766. else {
  63767. _this.mustUpdateRessources = true;
  63768. updateInDBCallback();
  63769. }
  63770. };
  63771. transaction.onabort = function (event) {
  63772. callback(-1);
  63773. };
  63774. var getRequest = transaction.objectStore("versions").get(url);
  63775. getRequest.onsuccess = function (event) {
  63776. version = (event.target).result;
  63777. };
  63778. getRequest.onerror = function (event) {
  63779. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  63780. callback(-1);
  63781. };
  63782. }
  63783. catch (ex) {
  63784. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  63785. callback(-1);
  63786. }
  63787. }
  63788. else {
  63789. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63790. callback(-1);
  63791. }
  63792. };
  63793. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  63794. var _this = this;
  63795. if (this.isSupported && !this.hasReachedQuota && this.db) {
  63796. try {
  63797. // Open a transaction to the database
  63798. var transaction = this.db.transaction(["versions"], "readwrite");
  63799. // the transaction could abort because of a QuotaExceededError error
  63800. transaction.onabort = function (event) {
  63801. try {
  63802. var error = event.srcElement['error'];
  63803. if (error && error.name === "QuotaExceededError") {
  63804. _this.hasReachedQuota = true;
  63805. }
  63806. }
  63807. catch (ex) { }
  63808. callback(-1);
  63809. };
  63810. transaction.oncomplete = function (event) {
  63811. callback(_this.manifestVersionFound);
  63812. };
  63813. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  63814. // Put the scene into the database
  63815. var addRequest = transaction.objectStore("versions").put(newVersion);
  63816. addRequest.onsuccess = function (event) {
  63817. };
  63818. addRequest.onerror = function (event) {
  63819. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  63820. };
  63821. }
  63822. catch (ex) {
  63823. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  63824. callback(-1);
  63825. }
  63826. }
  63827. else {
  63828. callback(-1);
  63829. }
  63830. };
  63831. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  63832. var _this = this;
  63833. var completeUrl = Database.ReturnFullUrlLocation(url);
  63834. var saveAndLoadFile = function () {
  63835. // the scene is not yet in the DB, let's try to save it
  63836. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  63837. };
  63838. this._checkVersionFromDB(completeUrl, function (version) {
  63839. if (version !== -1) {
  63840. if (!_this.mustUpdateRessources) {
  63841. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  63842. }
  63843. else {
  63844. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  63845. }
  63846. }
  63847. else {
  63848. if (errorCallback) {
  63849. errorCallback();
  63850. }
  63851. }
  63852. });
  63853. };
  63854. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  63855. if (this.isSupported && this.db) {
  63856. var targetStore;
  63857. if (url.indexOf(".babylon") !== -1) {
  63858. targetStore = "scenes";
  63859. }
  63860. else {
  63861. targetStore = "textures";
  63862. }
  63863. var file;
  63864. var transaction = this.db.transaction([targetStore]);
  63865. transaction.oncomplete = function (event) {
  63866. if (file) {
  63867. callback(file.data);
  63868. }
  63869. else {
  63870. notInDBCallback();
  63871. }
  63872. };
  63873. transaction.onabort = function (event) {
  63874. notInDBCallback();
  63875. };
  63876. var getRequest = transaction.objectStore(targetStore).get(url);
  63877. getRequest.onsuccess = function (event) {
  63878. file = (event.target).result;
  63879. };
  63880. getRequest.onerror = function (event) {
  63881. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  63882. notInDBCallback();
  63883. };
  63884. }
  63885. else {
  63886. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63887. callback();
  63888. }
  63889. };
  63890. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  63891. var _this = this;
  63892. if (this.isSupported) {
  63893. var targetStore;
  63894. if (url.indexOf(".babylon") !== -1) {
  63895. targetStore = "scenes";
  63896. }
  63897. else {
  63898. targetStore = "textures";
  63899. }
  63900. // Create XHR
  63901. var xhr = new XMLHttpRequest();
  63902. var fileData;
  63903. xhr.open("GET", url, true);
  63904. if (useArrayBuffer) {
  63905. xhr.responseType = "arraybuffer";
  63906. }
  63907. if (progressCallback) {
  63908. xhr.onprogress = progressCallback;
  63909. }
  63910. xhr.addEventListener("load", function () {
  63911. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  63912. // Blob as response (XHR2)
  63913. //fileData = xhr.responseText;
  63914. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  63915. if (!_this.hasReachedQuota && _this.db) {
  63916. // Open a transaction to the database
  63917. var transaction = _this.db.transaction([targetStore], "readwrite");
  63918. // the transaction could abort because of a QuotaExceededError error
  63919. transaction.onabort = function (event) {
  63920. try {
  63921. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  63922. var error = event.srcElement['error'];
  63923. if (error && error.name === "QuotaExceededError") {
  63924. _this.hasReachedQuota = true;
  63925. }
  63926. }
  63927. catch (ex) { }
  63928. callback(fileData);
  63929. };
  63930. transaction.oncomplete = function (event) {
  63931. callback(fileData);
  63932. };
  63933. var newFile;
  63934. if (targetStore === "scenes") {
  63935. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  63936. }
  63937. else {
  63938. newFile = { textureUrl: url, data: fileData };
  63939. }
  63940. try {
  63941. // Put the scene into the database
  63942. var addRequest = transaction.objectStore(targetStore).put(newFile);
  63943. addRequest.onsuccess = function (event) {
  63944. };
  63945. addRequest.onerror = function (event) {
  63946. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  63947. };
  63948. }
  63949. catch (ex) {
  63950. callback(fileData);
  63951. }
  63952. }
  63953. else {
  63954. callback(fileData);
  63955. }
  63956. }
  63957. else {
  63958. callback();
  63959. }
  63960. }, false);
  63961. xhr.addEventListener("error", function (event) {
  63962. BABYLON.Tools.Error("error on XHR request.");
  63963. callback();
  63964. }, false);
  63965. xhr.send();
  63966. }
  63967. else {
  63968. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63969. callback();
  63970. }
  63971. };
  63972. Database.IsUASupportingBlobStorage = true;
  63973. Database.IDBStorageEnabled = true;
  63974. Database.parseURL = function (url) {
  63975. var a = document.createElement('a');
  63976. a.href = url;
  63977. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  63978. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  63979. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  63980. return absLocation;
  63981. };
  63982. Database.ReturnFullUrlLocation = function (url) {
  63983. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  63984. return (Database.parseURL(window.location.href) + url);
  63985. }
  63986. else {
  63987. return url;
  63988. }
  63989. };
  63990. return Database;
  63991. }());
  63992. BABYLON.Database = Database;
  63993. })(BABYLON || (BABYLON = {}));
  63994. //# sourceMappingURL=babylon.database.js.map
  63995. "use strict";
  63996. var BABYLON;
  63997. (function (BABYLON) {
  63998. var FresnelParameters = /** @class */ (function () {
  63999. function FresnelParameters() {
  64000. this._isEnabled = true;
  64001. this.leftColor = BABYLON.Color3.White();
  64002. this.rightColor = BABYLON.Color3.Black();
  64003. this.bias = 0;
  64004. this.power = 1;
  64005. }
  64006. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  64007. get: function () {
  64008. return this._isEnabled;
  64009. },
  64010. set: function (value) {
  64011. if (this._isEnabled === value) {
  64012. return;
  64013. }
  64014. this._isEnabled = value;
  64015. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  64016. },
  64017. enumerable: true,
  64018. configurable: true
  64019. });
  64020. FresnelParameters.prototype.clone = function () {
  64021. var newFresnelParameters = new FresnelParameters();
  64022. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  64023. return newFresnelParameters;
  64024. };
  64025. FresnelParameters.prototype.serialize = function () {
  64026. var serializationObject = {};
  64027. serializationObject.isEnabled = this.isEnabled;
  64028. serializationObject.leftColor = this.leftColor;
  64029. serializationObject.rightColor = this.rightColor;
  64030. serializationObject.bias = this.bias;
  64031. serializationObject.power = this.power;
  64032. return serializationObject;
  64033. };
  64034. FresnelParameters.Parse = function (parsedFresnelParameters) {
  64035. var fresnelParameters = new FresnelParameters();
  64036. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  64037. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  64038. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  64039. fresnelParameters.bias = parsedFresnelParameters.bias;
  64040. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  64041. return fresnelParameters;
  64042. };
  64043. return FresnelParameters;
  64044. }());
  64045. BABYLON.FresnelParameters = FresnelParameters;
  64046. })(BABYLON || (BABYLON = {}));
  64047. //# sourceMappingURL=babylon.fresnelParameters.js.map
  64048. "use strict";
  64049. var BABYLON;
  64050. (function (BABYLON) {
  64051. var MultiMaterial = /** @class */ (function (_super) {
  64052. __extends(MultiMaterial, _super);
  64053. function MultiMaterial(name, scene) {
  64054. var _this = _super.call(this, name, scene, true) || this;
  64055. scene.multiMaterials.push(_this);
  64056. _this.subMaterials = new Array();
  64057. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  64058. return _this;
  64059. }
  64060. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  64061. get: function () {
  64062. return this._subMaterials;
  64063. },
  64064. set: function (value) {
  64065. this._subMaterials = value;
  64066. this._hookArray(value);
  64067. },
  64068. enumerable: true,
  64069. configurable: true
  64070. });
  64071. MultiMaterial.prototype._hookArray = function (array) {
  64072. var _this = this;
  64073. var oldPush = array.push;
  64074. array.push = function () {
  64075. var items = [];
  64076. for (var _i = 0; _i < arguments.length; _i++) {
  64077. items[_i] = arguments[_i];
  64078. }
  64079. var result = oldPush.apply(array, items);
  64080. _this._markAllSubMeshesAsTexturesDirty();
  64081. return result;
  64082. };
  64083. var oldSplice = array.splice;
  64084. array.splice = function (index, deleteCount) {
  64085. var deleted = oldSplice.apply(array, [index, deleteCount]);
  64086. _this._markAllSubMeshesAsTexturesDirty();
  64087. return deleted;
  64088. };
  64089. };
  64090. // Properties
  64091. MultiMaterial.prototype.getSubMaterial = function (index) {
  64092. if (index < 0 || index >= this.subMaterials.length) {
  64093. return this.getScene().defaultMaterial;
  64094. }
  64095. return this.subMaterials[index];
  64096. };
  64097. MultiMaterial.prototype.getActiveTextures = function () {
  64098. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  64099. if (subMaterial) {
  64100. return subMaterial.getActiveTextures();
  64101. }
  64102. else {
  64103. return [];
  64104. }
  64105. }));
  64106. var _a;
  64107. };
  64108. // Methods
  64109. MultiMaterial.prototype.getClassName = function () {
  64110. return "MultiMaterial";
  64111. };
  64112. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  64113. for (var index = 0; index < this.subMaterials.length; index++) {
  64114. var subMaterial = this.subMaterials[index];
  64115. if (subMaterial) {
  64116. if (subMaterial.storeEffectOnSubMeshes) {
  64117. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  64118. return false;
  64119. }
  64120. continue;
  64121. }
  64122. if (!subMaterial.isReady(mesh)) {
  64123. return false;
  64124. }
  64125. }
  64126. }
  64127. return true;
  64128. };
  64129. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  64130. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  64131. for (var index = 0; index < this.subMaterials.length; index++) {
  64132. var subMaterial = null;
  64133. var current = this.subMaterials[index];
  64134. if (cloneChildren && current) {
  64135. subMaterial = current.clone(name + "-" + current.name);
  64136. }
  64137. else {
  64138. subMaterial = this.subMaterials[index];
  64139. }
  64140. newMultiMaterial.subMaterials.push(subMaterial);
  64141. }
  64142. return newMultiMaterial;
  64143. };
  64144. MultiMaterial.prototype.serialize = function () {
  64145. var serializationObject = {};
  64146. serializationObject.name = this.name;
  64147. serializationObject.id = this.id;
  64148. if (BABYLON.Tags) {
  64149. serializationObject.tags = BABYLON.Tags.GetTags(this);
  64150. }
  64151. serializationObject.materials = [];
  64152. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  64153. var subMat = this.subMaterials[matIndex];
  64154. if (subMat) {
  64155. serializationObject.materials.push(subMat.id);
  64156. }
  64157. else {
  64158. serializationObject.materials.push(null);
  64159. }
  64160. }
  64161. return serializationObject;
  64162. };
  64163. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  64164. var scene = this.getScene();
  64165. if (!scene) {
  64166. return;
  64167. }
  64168. var index = scene.multiMaterials.indexOf(this);
  64169. if (index >= 0) {
  64170. scene.multiMaterials.splice(index, 1);
  64171. }
  64172. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  64173. };
  64174. return MultiMaterial;
  64175. }(BABYLON.Material));
  64176. BABYLON.MultiMaterial = MultiMaterial;
  64177. })(BABYLON || (BABYLON = {}));
  64178. //# sourceMappingURL=babylon.multiMaterial.js.map
  64179. "use strict";
  64180. var BABYLON;
  64181. (function (BABYLON) {
  64182. var FreeCameraTouchInput = /** @class */ (function () {
  64183. function FreeCameraTouchInput() {
  64184. this._offsetX = null;
  64185. this._offsetY = null;
  64186. this._pointerPressed = new Array();
  64187. this.touchAngularSensibility = 200000.0;
  64188. this.touchMoveSensibility = 250.0;
  64189. }
  64190. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  64191. var _this = this;
  64192. var previousPosition = null;
  64193. if (this._pointerInput === undefined) {
  64194. this._onLostFocus = function (evt) {
  64195. _this._offsetX = null;
  64196. _this._offsetY = null;
  64197. };
  64198. this._pointerInput = function (p, s) {
  64199. var evt = p.event;
  64200. if (evt.pointerType === "mouse") {
  64201. return;
  64202. }
  64203. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  64204. if (!noPreventDefault) {
  64205. evt.preventDefault();
  64206. }
  64207. _this._pointerPressed.push(evt.pointerId);
  64208. if (_this._pointerPressed.length !== 1) {
  64209. return;
  64210. }
  64211. previousPosition = {
  64212. x: evt.clientX,
  64213. y: evt.clientY
  64214. };
  64215. }
  64216. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  64217. if (!noPreventDefault) {
  64218. evt.preventDefault();
  64219. }
  64220. var index = _this._pointerPressed.indexOf(evt.pointerId);
  64221. if (index === -1) {
  64222. return;
  64223. }
  64224. _this._pointerPressed.splice(index, 1);
  64225. if (index != 0) {
  64226. return;
  64227. }
  64228. previousPosition = null;
  64229. _this._offsetX = null;
  64230. _this._offsetY = null;
  64231. }
  64232. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  64233. if (!noPreventDefault) {
  64234. evt.preventDefault();
  64235. }
  64236. if (!previousPosition) {
  64237. return;
  64238. }
  64239. var index = _this._pointerPressed.indexOf(evt.pointerId);
  64240. if (index != 0) {
  64241. return;
  64242. }
  64243. _this._offsetX = evt.clientX - previousPosition.x;
  64244. _this._offsetY = -(evt.clientY - previousPosition.y);
  64245. }
  64246. };
  64247. }
  64248. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  64249. if (this._onLostFocus) {
  64250. element.addEventListener("blur", this._onLostFocus);
  64251. }
  64252. };
  64253. FreeCameraTouchInput.prototype.detachControl = function (element) {
  64254. if (this._pointerInput && element) {
  64255. if (this._observer) {
  64256. this.camera.getScene().onPointerObservable.remove(this._observer);
  64257. this._observer = null;
  64258. }
  64259. if (this._onLostFocus) {
  64260. element.removeEventListener("blur", this._onLostFocus);
  64261. this._onLostFocus = null;
  64262. }
  64263. this._pointerPressed = [];
  64264. this._offsetX = null;
  64265. this._offsetY = null;
  64266. }
  64267. };
  64268. FreeCameraTouchInput.prototype.checkInputs = function () {
  64269. if (this._offsetX && this._offsetY) {
  64270. var camera = this.camera;
  64271. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  64272. if (this._pointerPressed.length > 1) {
  64273. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  64274. }
  64275. else {
  64276. var speed = camera._computeLocalCameraSpeed();
  64277. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  64278. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  64279. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  64280. }
  64281. }
  64282. };
  64283. FreeCameraTouchInput.prototype.getClassName = function () {
  64284. return "FreeCameraTouchInput";
  64285. };
  64286. FreeCameraTouchInput.prototype.getSimpleName = function () {
  64287. return "touch";
  64288. };
  64289. __decorate([
  64290. BABYLON.serialize()
  64291. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  64292. __decorate([
  64293. BABYLON.serialize()
  64294. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  64295. return FreeCameraTouchInput;
  64296. }());
  64297. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  64298. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  64299. })(BABYLON || (BABYLON = {}));
  64300. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  64301. "use strict";
  64302. var BABYLON;
  64303. (function (BABYLON) {
  64304. // We're mainly based on the logic defined into the FreeCamera code
  64305. var TouchCamera = /** @class */ (function (_super) {
  64306. __extends(TouchCamera, _super);
  64307. //-- end properties for backward compatibility for inputs
  64308. function TouchCamera(name, position, scene) {
  64309. var _this = _super.call(this, name, position, scene) || this;
  64310. _this.inputs.addTouch();
  64311. _this._setupInputs();
  64312. return _this;
  64313. }
  64314. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  64315. //-- Begin properties for backward compatibility for inputs
  64316. get: function () {
  64317. var touch = this.inputs.attached["touch"];
  64318. if (touch)
  64319. return touch.touchAngularSensibility;
  64320. return 0;
  64321. },
  64322. set: function (value) {
  64323. var touch = this.inputs.attached["touch"];
  64324. if (touch)
  64325. touch.touchAngularSensibility = value;
  64326. },
  64327. enumerable: true,
  64328. configurable: true
  64329. });
  64330. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  64331. get: function () {
  64332. var touch = this.inputs.attached["touch"];
  64333. if (touch)
  64334. return touch.touchMoveSensibility;
  64335. return 0;
  64336. },
  64337. set: function (value) {
  64338. var touch = this.inputs.attached["touch"];
  64339. if (touch)
  64340. touch.touchMoveSensibility = value;
  64341. },
  64342. enumerable: true,
  64343. configurable: true
  64344. });
  64345. TouchCamera.prototype.getClassName = function () {
  64346. return "TouchCamera";
  64347. };
  64348. TouchCamera.prototype._setupInputs = function () {
  64349. var mouse = this.inputs.attached["mouse"];
  64350. if (mouse) {
  64351. mouse.touchEnabled = false;
  64352. }
  64353. };
  64354. return TouchCamera;
  64355. }(BABYLON.FreeCamera));
  64356. BABYLON.TouchCamera = TouchCamera;
  64357. })(BABYLON || (BABYLON = {}));
  64358. //# sourceMappingURL=babylon.touchCamera.js.map
  64359. "use strict";
  64360. var BABYLON;
  64361. (function (BABYLON) {
  64362. var ProceduralTexture = /** @class */ (function (_super) {
  64363. __extends(ProceduralTexture, _super);
  64364. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  64365. if (fallbackTexture === void 0) { fallbackTexture = null; }
  64366. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64367. if (isCube === void 0) { isCube = false; }
  64368. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  64369. _this.isCube = isCube;
  64370. _this.isEnabled = true;
  64371. _this._currentRefreshId = -1;
  64372. _this._refreshRate = 1;
  64373. _this._vertexBuffers = {};
  64374. _this._uniforms = new Array();
  64375. _this._samplers = new Array();
  64376. _this._textures = {};
  64377. _this._floats = {};
  64378. _this._floatsArrays = {};
  64379. _this._colors3 = {};
  64380. _this._colors4 = {};
  64381. _this._vectors2 = {};
  64382. _this._vectors3 = {};
  64383. _this._matrices = {};
  64384. _this._fallbackTextureUsed = false;
  64385. scene._proceduralTextures.push(_this);
  64386. _this._engine = scene.getEngine();
  64387. _this.name = name;
  64388. _this.isRenderTarget = true;
  64389. _this._size = size;
  64390. _this._generateMipMaps = generateMipMaps;
  64391. _this.setFragment(fragment);
  64392. _this._fallbackTexture = fallbackTexture;
  64393. if (isCube) {
  64394. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  64395. _this.setFloat("face", 0);
  64396. }
  64397. else {
  64398. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  64399. }
  64400. // VBO
  64401. var vertices = [];
  64402. vertices.push(1, 1);
  64403. vertices.push(-1, 1);
  64404. vertices.push(-1, -1);
  64405. vertices.push(1, -1);
  64406. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  64407. _this._createIndexBuffer();
  64408. return _this;
  64409. }
  64410. ProceduralTexture.prototype._createIndexBuffer = function () {
  64411. var engine = this._engine;
  64412. // Indices
  64413. var indices = [];
  64414. indices.push(0);
  64415. indices.push(1);
  64416. indices.push(2);
  64417. indices.push(0);
  64418. indices.push(2);
  64419. indices.push(3);
  64420. this._indexBuffer = engine.createIndexBuffer(indices);
  64421. };
  64422. ProceduralTexture.prototype._rebuild = function () {
  64423. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64424. if (vb) {
  64425. vb._rebuild();
  64426. }
  64427. this._createIndexBuffer();
  64428. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64429. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64430. }
  64431. };
  64432. ProceduralTexture.prototype.reset = function () {
  64433. if (this._effect === undefined) {
  64434. return;
  64435. }
  64436. var engine = this._engine;
  64437. engine._releaseEffect(this._effect);
  64438. };
  64439. ProceduralTexture.prototype.isReady = function () {
  64440. var _this = this;
  64441. var engine = this._engine;
  64442. var shaders;
  64443. if (!this._fragment) {
  64444. return false;
  64445. }
  64446. if (this._fallbackTextureUsed) {
  64447. return true;
  64448. }
  64449. if (this._fragment.fragmentElement !== undefined) {
  64450. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  64451. }
  64452. else {
  64453. shaders = { vertex: "procedural", fragment: this._fragment };
  64454. }
  64455. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  64456. _this.releaseInternalTexture();
  64457. if (_this._fallbackTexture) {
  64458. _this._texture = _this._fallbackTexture._texture;
  64459. if (_this._texture) {
  64460. _this._texture.incrementReferences();
  64461. }
  64462. }
  64463. _this._fallbackTextureUsed = true;
  64464. });
  64465. return this._effect.isReady();
  64466. };
  64467. ProceduralTexture.prototype.resetRefreshCounter = function () {
  64468. this._currentRefreshId = -1;
  64469. };
  64470. ProceduralTexture.prototype.setFragment = function (fragment) {
  64471. this._fragment = fragment;
  64472. };
  64473. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  64474. get: function () {
  64475. return this._refreshRate;
  64476. },
  64477. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  64478. set: function (value) {
  64479. this._refreshRate = value;
  64480. this.resetRefreshCounter();
  64481. },
  64482. enumerable: true,
  64483. configurable: true
  64484. });
  64485. ProceduralTexture.prototype._shouldRender = function () {
  64486. if (!this.isEnabled || !this.isReady() || !this._texture) {
  64487. return false;
  64488. }
  64489. if (this._fallbackTextureUsed) {
  64490. return false;
  64491. }
  64492. if (this._currentRefreshId === -1) {
  64493. this._currentRefreshId = 1;
  64494. return true;
  64495. }
  64496. if (this.refreshRate === this._currentRefreshId) {
  64497. this._currentRefreshId = 1;
  64498. return true;
  64499. }
  64500. this._currentRefreshId++;
  64501. return false;
  64502. };
  64503. ProceduralTexture.prototype.getRenderSize = function () {
  64504. return this._size;
  64505. };
  64506. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  64507. if (this._fallbackTextureUsed) {
  64508. return;
  64509. }
  64510. this.releaseInternalTexture();
  64511. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  64512. };
  64513. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  64514. if (this._uniforms.indexOf(uniformName) === -1) {
  64515. this._uniforms.push(uniformName);
  64516. }
  64517. };
  64518. ProceduralTexture.prototype.setTexture = function (name, texture) {
  64519. if (this._samplers.indexOf(name) === -1) {
  64520. this._samplers.push(name);
  64521. }
  64522. this._textures[name] = texture;
  64523. return this;
  64524. };
  64525. ProceduralTexture.prototype.setFloat = function (name, value) {
  64526. this._checkUniform(name);
  64527. this._floats[name] = value;
  64528. return this;
  64529. };
  64530. ProceduralTexture.prototype.setFloats = function (name, value) {
  64531. this._checkUniform(name);
  64532. this._floatsArrays[name] = value;
  64533. return this;
  64534. };
  64535. ProceduralTexture.prototype.setColor3 = function (name, value) {
  64536. this._checkUniform(name);
  64537. this._colors3[name] = value;
  64538. return this;
  64539. };
  64540. ProceduralTexture.prototype.setColor4 = function (name, value) {
  64541. this._checkUniform(name);
  64542. this._colors4[name] = value;
  64543. return this;
  64544. };
  64545. ProceduralTexture.prototype.setVector2 = function (name, value) {
  64546. this._checkUniform(name);
  64547. this._vectors2[name] = value;
  64548. return this;
  64549. };
  64550. ProceduralTexture.prototype.setVector3 = function (name, value) {
  64551. this._checkUniform(name);
  64552. this._vectors3[name] = value;
  64553. return this;
  64554. };
  64555. ProceduralTexture.prototype.setMatrix = function (name, value) {
  64556. this._checkUniform(name);
  64557. this._matrices[name] = value;
  64558. return this;
  64559. };
  64560. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  64561. var scene = this.getScene();
  64562. if (!scene) {
  64563. return;
  64564. }
  64565. var engine = this._engine;
  64566. // Render
  64567. engine.enableEffect(this._effect);
  64568. engine.setState(false);
  64569. // Texture
  64570. for (var name in this._textures) {
  64571. this._effect.setTexture(name, this._textures[name]);
  64572. }
  64573. // Float
  64574. for (name in this._floats) {
  64575. this._effect.setFloat(name, this._floats[name]);
  64576. }
  64577. // Floats
  64578. for (name in this._floatsArrays) {
  64579. this._effect.setArray(name, this._floatsArrays[name]);
  64580. }
  64581. // Color3
  64582. for (name in this._colors3) {
  64583. this._effect.setColor3(name, this._colors3[name]);
  64584. }
  64585. // Color4
  64586. for (name in this._colors4) {
  64587. var color = this._colors4[name];
  64588. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  64589. }
  64590. // Vector2
  64591. for (name in this._vectors2) {
  64592. this._effect.setVector2(name, this._vectors2[name]);
  64593. }
  64594. // Vector3
  64595. for (name in this._vectors3) {
  64596. this._effect.setVector3(name, this._vectors3[name]);
  64597. }
  64598. // Matrix
  64599. for (name in this._matrices) {
  64600. this._effect.setMatrix(name, this._matrices[name]);
  64601. }
  64602. if (!this._texture) {
  64603. return;
  64604. }
  64605. if (this.isCube) {
  64606. for (var face = 0; face < 6; face++) {
  64607. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  64608. // VBOs
  64609. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  64610. this._effect.setFloat("face", face);
  64611. // Clear
  64612. engine.clear(scene.clearColor, true, true, true);
  64613. // Draw order
  64614. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64615. // Mipmaps
  64616. if (face === 5) {
  64617. engine.generateMipMapsForCubemap(this._texture);
  64618. }
  64619. }
  64620. }
  64621. else {
  64622. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  64623. // VBOs
  64624. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  64625. // Clear
  64626. engine.clear(scene.clearColor, true, true, true);
  64627. // Draw order
  64628. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64629. }
  64630. // Unbind
  64631. engine.unBindFramebuffer(this._texture, this.isCube);
  64632. if (this.onGenerated) {
  64633. this.onGenerated();
  64634. }
  64635. };
  64636. ProceduralTexture.prototype.clone = function () {
  64637. var textureSize = this.getSize();
  64638. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  64639. // Base texture
  64640. newTexture.hasAlpha = this.hasAlpha;
  64641. newTexture.level = this.level;
  64642. // RenderTarget Texture
  64643. newTexture.coordinatesMode = this.coordinatesMode;
  64644. return newTexture;
  64645. };
  64646. ProceduralTexture.prototype.dispose = function () {
  64647. var scene = this.getScene();
  64648. if (!scene) {
  64649. return;
  64650. }
  64651. var index = scene._proceduralTextures.indexOf(this);
  64652. if (index >= 0) {
  64653. scene._proceduralTextures.splice(index, 1);
  64654. }
  64655. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64656. if (vertexBuffer) {
  64657. vertexBuffer.dispose();
  64658. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64659. }
  64660. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  64661. this._indexBuffer = null;
  64662. }
  64663. _super.prototype.dispose.call(this);
  64664. };
  64665. return ProceduralTexture;
  64666. }(BABYLON.Texture));
  64667. BABYLON.ProceduralTexture = ProceduralTexture;
  64668. })(BABYLON || (BABYLON = {}));
  64669. //# sourceMappingURL=babylon.proceduralTexture.js.map
  64670. "use strict";
  64671. var BABYLON;
  64672. (function (BABYLON) {
  64673. var CustomProceduralTexture = /** @class */ (function (_super) {
  64674. __extends(CustomProceduralTexture, _super);
  64675. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  64676. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  64677. _this._animate = true;
  64678. _this._time = 0;
  64679. _this._texturePath = texturePath;
  64680. //Try to load json
  64681. _this.loadJson(texturePath);
  64682. _this.refreshRate = 1;
  64683. return _this;
  64684. }
  64685. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  64686. var _this = this;
  64687. var noConfigFile = function () {
  64688. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  64689. try {
  64690. _this.setFragment(_this._texturePath);
  64691. }
  64692. catch (ex) {
  64693. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  64694. }
  64695. };
  64696. var configFileUrl = jsonUrl + "/config.json";
  64697. var xhr = new XMLHttpRequest();
  64698. xhr.open("GET", configFileUrl, true);
  64699. xhr.addEventListener("load", function () {
  64700. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  64701. try {
  64702. _this._config = JSON.parse(xhr.response);
  64703. _this.updateShaderUniforms();
  64704. _this.updateTextures();
  64705. _this.setFragment(_this._texturePath + "/custom");
  64706. _this._animate = _this._config.animate;
  64707. _this.refreshRate = _this._config.refreshrate;
  64708. }
  64709. catch (ex) {
  64710. noConfigFile();
  64711. }
  64712. }
  64713. else {
  64714. noConfigFile();
  64715. }
  64716. }, false);
  64717. xhr.addEventListener("error", function () {
  64718. noConfigFile();
  64719. }, false);
  64720. try {
  64721. xhr.send();
  64722. }
  64723. catch (ex) {
  64724. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  64725. }
  64726. };
  64727. CustomProceduralTexture.prototype.isReady = function () {
  64728. if (!_super.prototype.isReady.call(this)) {
  64729. return false;
  64730. }
  64731. for (var name in this._textures) {
  64732. var texture = this._textures[name];
  64733. if (!texture.isReady()) {
  64734. return false;
  64735. }
  64736. }
  64737. return true;
  64738. };
  64739. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  64740. var scene = this.getScene();
  64741. if (this._animate && scene) {
  64742. this._time += scene.getAnimationRatio() * 0.03;
  64743. this.updateShaderUniforms();
  64744. }
  64745. _super.prototype.render.call(this, useCameraPostProcess);
  64746. };
  64747. CustomProceduralTexture.prototype.updateTextures = function () {
  64748. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  64749. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  64750. }
  64751. };
  64752. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  64753. if (this._config) {
  64754. for (var j = 0; j < this._config.uniforms.length; j++) {
  64755. var uniform = this._config.uniforms[j];
  64756. switch (uniform.type) {
  64757. case "float":
  64758. this.setFloat(uniform.name, uniform.value);
  64759. break;
  64760. case "color3":
  64761. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  64762. break;
  64763. case "color4":
  64764. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  64765. break;
  64766. case "vector2":
  64767. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  64768. break;
  64769. case "vector3":
  64770. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  64771. break;
  64772. }
  64773. }
  64774. }
  64775. this.setFloat("time", this._time);
  64776. };
  64777. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  64778. get: function () {
  64779. return this._animate;
  64780. },
  64781. set: function (value) {
  64782. this._animate = value;
  64783. },
  64784. enumerable: true,
  64785. configurable: true
  64786. });
  64787. return CustomProceduralTexture;
  64788. }(BABYLON.ProceduralTexture));
  64789. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  64790. })(BABYLON || (BABYLON = {}));
  64791. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  64792. "use strict";
  64793. var BABYLON;
  64794. (function (BABYLON) {
  64795. var FreeCameraGamepadInput = /** @class */ (function () {
  64796. function FreeCameraGamepadInput() {
  64797. this.gamepadAngularSensibility = 200;
  64798. this.gamepadMoveSensibility = 40;
  64799. // private members
  64800. this._cameraTransform = BABYLON.Matrix.Identity();
  64801. this._deltaTransform = BABYLON.Vector3.Zero();
  64802. this._vector3 = BABYLON.Vector3.Zero();
  64803. this._vector2 = BABYLON.Vector2.Zero();
  64804. }
  64805. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  64806. var _this = this;
  64807. var manager = this.camera.getScene().gamepadManager;
  64808. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  64809. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  64810. // prioritize XBOX gamepads.
  64811. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  64812. _this.gamepad = gamepad;
  64813. }
  64814. }
  64815. });
  64816. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  64817. if (_this.gamepad === gamepad) {
  64818. _this.gamepad = null;
  64819. }
  64820. });
  64821. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  64822. };
  64823. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  64824. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  64825. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  64826. this.gamepad = null;
  64827. };
  64828. FreeCameraGamepadInput.prototype.checkInputs = function () {
  64829. if (this.gamepad && this.gamepad.leftStick) {
  64830. var camera = this.camera;
  64831. var LSValues = this.gamepad.leftStick;
  64832. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  64833. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  64834. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  64835. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  64836. var RSValues = this.gamepad.rightStick;
  64837. if (RSValues) {
  64838. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  64839. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  64840. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  64841. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  64842. }
  64843. else {
  64844. RSValues = { x: 0, y: 0 };
  64845. }
  64846. if (!camera.rotationQuaternion) {
  64847. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  64848. }
  64849. else {
  64850. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  64851. }
  64852. var speed = camera._computeLocalCameraSpeed() * 50.0;
  64853. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  64854. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  64855. camera.cameraDirection.addInPlace(this._deltaTransform);
  64856. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  64857. camera.cameraRotation.addInPlace(this._vector2);
  64858. }
  64859. };
  64860. FreeCameraGamepadInput.prototype.getClassName = function () {
  64861. return "FreeCameraGamepadInput";
  64862. };
  64863. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  64864. return "gamepad";
  64865. };
  64866. __decorate([
  64867. BABYLON.serialize()
  64868. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  64869. __decorate([
  64870. BABYLON.serialize()
  64871. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  64872. return FreeCameraGamepadInput;
  64873. }());
  64874. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  64875. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  64876. })(BABYLON || (BABYLON = {}));
  64877. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  64878. "use strict";
  64879. var BABYLON;
  64880. (function (BABYLON) {
  64881. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  64882. function ArcRotateCameraGamepadInput() {
  64883. this.gamepadRotationSensibility = 80;
  64884. this.gamepadMoveSensibility = 40;
  64885. }
  64886. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  64887. var _this = this;
  64888. var manager = this.camera.getScene().gamepadManager;
  64889. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  64890. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  64891. // prioritize XBOX gamepads.
  64892. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  64893. _this.gamepad = gamepad;
  64894. }
  64895. }
  64896. });
  64897. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  64898. if (_this.gamepad === gamepad) {
  64899. _this.gamepad = null;
  64900. }
  64901. });
  64902. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  64903. };
  64904. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  64905. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  64906. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  64907. this.gamepad = null;
  64908. };
  64909. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  64910. if (this.gamepad) {
  64911. var camera = this.camera;
  64912. var RSValues = this.gamepad.rightStick;
  64913. if (RSValues) {
  64914. if (RSValues.x != 0) {
  64915. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  64916. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  64917. camera.inertialAlphaOffset += normalizedRX;
  64918. }
  64919. }
  64920. if (RSValues.y != 0) {
  64921. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  64922. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  64923. camera.inertialBetaOffset += normalizedRY;
  64924. }
  64925. }
  64926. }
  64927. var LSValues = this.gamepad.leftStick;
  64928. if (LSValues && LSValues.y != 0) {
  64929. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  64930. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  64931. this.camera.inertialRadiusOffset -= normalizedLY;
  64932. }
  64933. }
  64934. }
  64935. };
  64936. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  64937. return "ArcRotateCameraGamepadInput";
  64938. };
  64939. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  64940. return "gamepad";
  64941. };
  64942. __decorate([
  64943. BABYLON.serialize()
  64944. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  64945. __decorate([
  64946. BABYLON.serialize()
  64947. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  64948. return ArcRotateCameraGamepadInput;
  64949. }());
  64950. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  64951. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  64952. })(BABYLON || (BABYLON = {}));
  64953. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  64954. "use strict";
  64955. var BABYLON;
  64956. (function (BABYLON) {
  64957. var GamepadManager = /** @class */ (function () {
  64958. function GamepadManager(_scene) {
  64959. var _this = this;
  64960. this._scene = _scene;
  64961. this._babylonGamepads = [];
  64962. this._oneGamepadConnected = false;
  64963. this._isMonitoring = false;
  64964. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  64965. if (!BABYLON.Tools.IsWindowObjectExist()) {
  64966. this._gamepadEventSupported = false;
  64967. }
  64968. else {
  64969. this._gamepadEventSupported = 'GamepadEvent' in window;
  64970. this._gamepadSupport = (navigator.getGamepads ||
  64971. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  64972. }
  64973. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  64974. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  64975. for (var i in _this._babylonGamepads) {
  64976. var gamepad = _this._babylonGamepads[i];
  64977. if (gamepad && gamepad._isConnected) {
  64978. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  64979. }
  64980. }
  64981. });
  64982. this._onGamepadConnectedEvent = function (evt) {
  64983. var gamepad = evt.gamepad;
  64984. if (gamepad.index in _this._babylonGamepads) {
  64985. if (_this._babylonGamepads[gamepad.index].isConnected) {
  64986. return;
  64987. }
  64988. }
  64989. var newGamepad;
  64990. if (_this._babylonGamepads[gamepad.index]) {
  64991. newGamepad = _this._babylonGamepads[gamepad.index];
  64992. newGamepad.browserGamepad = gamepad;
  64993. newGamepad._isConnected = true;
  64994. }
  64995. else {
  64996. newGamepad = _this._addNewGamepad(gamepad);
  64997. }
  64998. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  64999. _this._startMonitoringGamepads();
  65000. };
  65001. this._onGamepadDisconnectedEvent = function (evt) {
  65002. var gamepad = evt.gamepad;
  65003. // Remove the gamepad from the list of gamepads to monitor.
  65004. for (var i in _this._babylonGamepads) {
  65005. if (_this._babylonGamepads[i].index === gamepad.index) {
  65006. var disconnectedGamepad = _this._babylonGamepads[i];
  65007. disconnectedGamepad._isConnected = false;
  65008. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  65009. break;
  65010. }
  65011. }
  65012. };
  65013. if (this._gamepadSupport) {
  65014. //first add already-connected gamepads
  65015. this._updateGamepadObjects();
  65016. if (this._babylonGamepads.length) {
  65017. this._startMonitoringGamepads();
  65018. }
  65019. // Checking if the gamepad connected event is supported (like in Firefox)
  65020. if (this._gamepadEventSupported) {
  65021. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  65022. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  65023. }
  65024. else {
  65025. this._startMonitoringGamepads();
  65026. }
  65027. }
  65028. }
  65029. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  65030. get: function () {
  65031. return this._babylonGamepads;
  65032. },
  65033. enumerable: true,
  65034. configurable: true
  65035. });
  65036. GamepadManager.prototype.getGamepadByType = function (type) {
  65037. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  65038. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  65039. var gamepad = _a[_i];
  65040. if (gamepad && gamepad.type === type) {
  65041. return gamepad;
  65042. }
  65043. }
  65044. return null;
  65045. };
  65046. GamepadManager.prototype.dispose = function () {
  65047. if (this._gamepadEventSupported) {
  65048. if (this._onGamepadConnectedEvent) {
  65049. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  65050. }
  65051. if (this._onGamepadDisconnectedEvent) {
  65052. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  65053. }
  65054. this._onGamepadConnectedEvent = null;
  65055. this._onGamepadDisconnectedEvent = null;
  65056. }
  65057. this._babylonGamepads.forEach(function (gamepad) {
  65058. gamepad.dispose();
  65059. });
  65060. this.onGamepadConnectedObservable.clear();
  65061. this.onGamepadDisconnectedObservable.clear();
  65062. this._oneGamepadConnected = false;
  65063. this._stopMonitoringGamepads();
  65064. this._babylonGamepads = [];
  65065. };
  65066. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  65067. if (!this._oneGamepadConnected) {
  65068. this._oneGamepadConnected = true;
  65069. }
  65070. var newGamepad;
  65071. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  65072. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  65073. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  65074. }
  65075. else if (gamepad.pose) {
  65076. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  65077. }
  65078. else {
  65079. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  65080. }
  65081. this._babylonGamepads[newGamepad.index] = newGamepad;
  65082. return newGamepad;
  65083. };
  65084. GamepadManager.prototype._startMonitoringGamepads = function () {
  65085. if (!this._isMonitoring) {
  65086. this._isMonitoring = true;
  65087. //back-comp
  65088. if (!this._scene) {
  65089. this._checkGamepadsStatus();
  65090. }
  65091. }
  65092. };
  65093. GamepadManager.prototype._stopMonitoringGamepads = function () {
  65094. this._isMonitoring = false;
  65095. };
  65096. GamepadManager.prototype._checkGamepadsStatus = function () {
  65097. var _this = this;
  65098. // Hack to be compatible Chrome
  65099. this._updateGamepadObjects();
  65100. for (var i in this._babylonGamepads) {
  65101. var gamepad = this._babylonGamepads[i];
  65102. if (!gamepad || !gamepad.isConnected) {
  65103. continue;
  65104. }
  65105. gamepad.update();
  65106. }
  65107. if (this._isMonitoring && !this._scene) {
  65108. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  65109. }
  65110. };
  65111. // This function is called only on Chrome, which does not properly support
  65112. // connection/disconnection events and forces you to recopy again the gamepad object
  65113. GamepadManager.prototype._updateGamepadObjects = function () {
  65114. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  65115. for (var i = 0; i < gamepads.length; i++) {
  65116. if (gamepads[i]) {
  65117. if (!this._babylonGamepads[gamepads[i].index]) {
  65118. var newGamepad = this._addNewGamepad(gamepads[i]);
  65119. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  65120. }
  65121. else {
  65122. // Forced to copy again this object for Chrome for unknown reason
  65123. this._babylonGamepads[i].browserGamepad = gamepads[i];
  65124. if (!this._babylonGamepads[i].isConnected) {
  65125. this._babylonGamepads[i]._isConnected = true;
  65126. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  65127. }
  65128. }
  65129. }
  65130. }
  65131. };
  65132. return GamepadManager;
  65133. }());
  65134. BABYLON.GamepadManager = GamepadManager;
  65135. })(BABYLON || (BABYLON = {}));
  65136. //# sourceMappingURL=babylon.gamepadManager.js.map
  65137. "use strict";
  65138. var BABYLON;
  65139. (function (BABYLON) {
  65140. var StickValues = /** @class */ (function () {
  65141. function StickValues(x, y) {
  65142. this.x = x;
  65143. this.y = y;
  65144. }
  65145. return StickValues;
  65146. }());
  65147. BABYLON.StickValues = StickValues;
  65148. var Gamepad = /** @class */ (function () {
  65149. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  65150. if (leftStickX === void 0) { leftStickX = 0; }
  65151. if (leftStickY === void 0) { leftStickY = 1; }
  65152. if (rightStickX === void 0) { rightStickX = 2; }
  65153. if (rightStickY === void 0) { rightStickY = 3; }
  65154. this.id = id;
  65155. this.index = index;
  65156. this.browserGamepad = browserGamepad;
  65157. this._isConnected = true;
  65158. this._invertLeftStickY = false;
  65159. this.type = Gamepad.GAMEPAD;
  65160. this._leftStickAxisX = leftStickX;
  65161. this._leftStickAxisY = leftStickY;
  65162. this._rightStickAxisX = rightStickX;
  65163. this._rightStickAxisY = rightStickY;
  65164. if (this.browserGamepad.axes.length >= 2) {
  65165. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  65166. }
  65167. if (this.browserGamepad.axes.length >= 4) {
  65168. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  65169. }
  65170. }
  65171. Object.defineProperty(Gamepad.prototype, "isConnected", {
  65172. get: function () {
  65173. return this._isConnected;
  65174. },
  65175. enumerable: true,
  65176. configurable: true
  65177. });
  65178. Gamepad.prototype.onleftstickchanged = function (callback) {
  65179. this._onleftstickchanged = callback;
  65180. };
  65181. Gamepad.prototype.onrightstickchanged = function (callback) {
  65182. this._onrightstickchanged = callback;
  65183. };
  65184. Object.defineProperty(Gamepad.prototype, "leftStick", {
  65185. get: function () {
  65186. return this._leftStick;
  65187. },
  65188. set: function (newValues) {
  65189. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  65190. this._onleftstickchanged(newValues);
  65191. }
  65192. this._leftStick = newValues;
  65193. },
  65194. enumerable: true,
  65195. configurable: true
  65196. });
  65197. Object.defineProperty(Gamepad.prototype, "rightStick", {
  65198. get: function () {
  65199. return this._rightStick;
  65200. },
  65201. set: function (newValues) {
  65202. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  65203. this._onrightstickchanged(newValues);
  65204. }
  65205. this._rightStick = newValues;
  65206. },
  65207. enumerable: true,
  65208. configurable: true
  65209. });
  65210. Gamepad.prototype.update = function () {
  65211. if (this._leftStick) {
  65212. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  65213. if (this._invertLeftStickY) {
  65214. this.leftStick.y *= -1;
  65215. }
  65216. }
  65217. if (this._rightStick) {
  65218. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  65219. }
  65220. };
  65221. Gamepad.prototype.dispose = function () {
  65222. };
  65223. Gamepad.GAMEPAD = 0;
  65224. Gamepad.GENERIC = 1;
  65225. Gamepad.XBOX = 2;
  65226. Gamepad.POSE_ENABLED = 3;
  65227. return Gamepad;
  65228. }());
  65229. BABYLON.Gamepad = Gamepad;
  65230. var GenericPad = /** @class */ (function (_super) {
  65231. __extends(GenericPad, _super);
  65232. function GenericPad(id, index, browserGamepad) {
  65233. var _this = _super.call(this, id, index, browserGamepad) || this;
  65234. _this.onButtonDownObservable = new BABYLON.Observable();
  65235. _this.onButtonUpObservable = new BABYLON.Observable();
  65236. _this.type = Gamepad.GENERIC;
  65237. _this._buttons = new Array(browserGamepad.buttons.length);
  65238. return _this;
  65239. }
  65240. GenericPad.prototype.onbuttondown = function (callback) {
  65241. this._onbuttondown = callback;
  65242. };
  65243. GenericPad.prototype.onbuttonup = function (callback) {
  65244. this._onbuttonup = callback;
  65245. };
  65246. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  65247. if (newValue !== currentValue) {
  65248. if (newValue === 1) {
  65249. if (this._onbuttondown) {
  65250. this._onbuttondown(buttonIndex);
  65251. }
  65252. this.onButtonDownObservable.notifyObservers(buttonIndex);
  65253. }
  65254. if (newValue === 0) {
  65255. if (this._onbuttonup) {
  65256. this._onbuttonup(buttonIndex);
  65257. }
  65258. this.onButtonUpObservable.notifyObservers(buttonIndex);
  65259. }
  65260. }
  65261. return newValue;
  65262. };
  65263. GenericPad.prototype.update = function () {
  65264. _super.prototype.update.call(this);
  65265. for (var index = 0; index < this._buttons.length; index++) {
  65266. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  65267. }
  65268. };
  65269. GenericPad.prototype.dispose = function () {
  65270. _super.prototype.dispose.call(this);
  65271. this.onButtonDownObservable.clear();
  65272. this.onButtonUpObservable.clear();
  65273. };
  65274. return GenericPad;
  65275. }(Gamepad));
  65276. BABYLON.GenericPad = GenericPad;
  65277. })(BABYLON || (BABYLON = {}));
  65278. //# sourceMappingURL=babylon.gamepad.js.map
  65279. "use strict";
  65280. var BABYLON;
  65281. (function (BABYLON) {
  65282. var Xbox360Button;
  65283. (function (Xbox360Button) {
  65284. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  65285. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  65286. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  65287. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  65288. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  65289. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  65290. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  65291. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  65292. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  65293. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  65294. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  65295. var Xbox360Dpad;
  65296. (function (Xbox360Dpad) {
  65297. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  65298. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  65299. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  65300. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  65301. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  65302. var Xbox360Pad = /** @class */ (function (_super) {
  65303. __extends(Xbox360Pad, _super);
  65304. function Xbox360Pad(id, index, gamepad, xboxOne) {
  65305. if (xboxOne === void 0) { xboxOne = false; }
  65306. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  65307. _this._leftTrigger = 0;
  65308. _this._rightTrigger = 0;
  65309. _this.onButtonDownObservable = new BABYLON.Observable();
  65310. _this.onButtonUpObservable = new BABYLON.Observable();
  65311. _this.onPadDownObservable = new BABYLON.Observable();
  65312. _this.onPadUpObservable = new BABYLON.Observable();
  65313. _this._buttonA = 0;
  65314. _this._buttonB = 0;
  65315. _this._buttonX = 0;
  65316. _this._buttonY = 0;
  65317. _this._buttonBack = 0;
  65318. _this._buttonStart = 0;
  65319. _this._buttonLB = 0;
  65320. _this._buttonRB = 0;
  65321. _this._buttonLeftStick = 0;
  65322. _this._buttonRightStick = 0;
  65323. _this._dPadUp = 0;
  65324. _this._dPadDown = 0;
  65325. _this._dPadLeft = 0;
  65326. _this._dPadRight = 0;
  65327. _this._isXboxOnePad = false;
  65328. _this.type = BABYLON.Gamepad.XBOX;
  65329. _this._isXboxOnePad = xboxOne;
  65330. return _this;
  65331. }
  65332. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  65333. this._onlefttriggerchanged = callback;
  65334. };
  65335. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  65336. this._onrighttriggerchanged = callback;
  65337. };
  65338. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  65339. get: function () {
  65340. return this._leftTrigger;
  65341. },
  65342. set: function (newValue) {
  65343. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  65344. this._onlefttriggerchanged(newValue);
  65345. }
  65346. this._leftTrigger = newValue;
  65347. },
  65348. enumerable: true,
  65349. configurable: true
  65350. });
  65351. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  65352. get: function () {
  65353. return this._rightTrigger;
  65354. },
  65355. set: function (newValue) {
  65356. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  65357. this._onrighttriggerchanged(newValue);
  65358. }
  65359. this._rightTrigger = newValue;
  65360. },
  65361. enumerable: true,
  65362. configurable: true
  65363. });
  65364. Xbox360Pad.prototype.onbuttondown = function (callback) {
  65365. this._onbuttondown = callback;
  65366. };
  65367. Xbox360Pad.prototype.onbuttonup = function (callback) {
  65368. this._onbuttonup = callback;
  65369. };
  65370. Xbox360Pad.prototype.ondpaddown = function (callback) {
  65371. this._ondpaddown = callback;
  65372. };
  65373. Xbox360Pad.prototype.ondpadup = function (callback) {
  65374. this._ondpadup = callback;
  65375. };
  65376. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  65377. if (newValue !== currentValue) {
  65378. if (newValue === 1) {
  65379. if (this._onbuttondown) {
  65380. this._onbuttondown(buttonType);
  65381. }
  65382. this.onButtonDownObservable.notifyObservers(buttonType);
  65383. }
  65384. if (newValue === 0) {
  65385. if (this._onbuttonup) {
  65386. this._onbuttonup(buttonType);
  65387. }
  65388. this.onButtonUpObservable.notifyObservers(buttonType);
  65389. }
  65390. }
  65391. return newValue;
  65392. };
  65393. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  65394. if (newValue !== currentValue) {
  65395. if (newValue === 1) {
  65396. if (this._ondpaddown) {
  65397. this._ondpaddown(buttonType);
  65398. }
  65399. this.onPadDownObservable.notifyObservers(buttonType);
  65400. }
  65401. if (newValue === 0) {
  65402. if (this._ondpadup) {
  65403. this._ondpadup(buttonType);
  65404. }
  65405. this.onPadUpObservable.notifyObservers(buttonType);
  65406. }
  65407. }
  65408. return newValue;
  65409. };
  65410. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  65411. get: function () {
  65412. return this._buttonA;
  65413. },
  65414. set: function (value) {
  65415. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  65416. },
  65417. enumerable: true,
  65418. configurable: true
  65419. });
  65420. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  65421. get: function () {
  65422. return this._buttonB;
  65423. },
  65424. set: function (value) {
  65425. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  65426. },
  65427. enumerable: true,
  65428. configurable: true
  65429. });
  65430. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  65431. get: function () {
  65432. return this._buttonX;
  65433. },
  65434. set: function (value) {
  65435. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  65436. },
  65437. enumerable: true,
  65438. configurable: true
  65439. });
  65440. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  65441. get: function () {
  65442. return this._buttonY;
  65443. },
  65444. set: function (value) {
  65445. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  65446. },
  65447. enumerable: true,
  65448. configurable: true
  65449. });
  65450. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  65451. get: function () {
  65452. return this._buttonStart;
  65453. },
  65454. set: function (value) {
  65455. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  65456. },
  65457. enumerable: true,
  65458. configurable: true
  65459. });
  65460. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  65461. get: function () {
  65462. return this._buttonBack;
  65463. },
  65464. set: function (value) {
  65465. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  65466. },
  65467. enumerable: true,
  65468. configurable: true
  65469. });
  65470. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  65471. get: function () {
  65472. return this._buttonLB;
  65473. },
  65474. set: function (value) {
  65475. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  65476. },
  65477. enumerable: true,
  65478. configurable: true
  65479. });
  65480. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  65481. get: function () {
  65482. return this._buttonRB;
  65483. },
  65484. set: function (value) {
  65485. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  65486. },
  65487. enumerable: true,
  65488. configurable: true
  65489. });
  65490. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  65491. get: function () {
  65492. return this._buttonLeftStick;
  65493. },
  65494. set: function (value) {
  65495. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  65496. },
  65497. enumerable: true,
  65498. configurable: true
  65499. });
  65500. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  65501. get: function () {
  65502. return this._buttonRightStick;
  65503. },
  65504. set: function (value) {
  65505. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  65506. },
  65507. enumerable: true,
  65508. configurable: true
  65509. });
  65510. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  65511. get: function () {
  65512. return this._dPadUp;
  65513. },
  65514. set: function (value) {
  65515. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  65516. },
  65517. enumerable: true,
  65518. configurable: true
  65519. });
  65520. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  65521. get: function () {
  65522. return this._dPadDown;
  65523. },
  65524. set: function (value) {
  65525. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  65526. },
  65527. enumerable: true,
  65528. configurable: true
  65529. });
  65530. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  65531. get: function () {
  65532. return this._dPadLeft;
  65533. },
  65534. set: function (value) {
  65535. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  65536. },
  65537. enumerable: true,
  65538. configurable: true
  65539. });
  65540. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  65541. get: function () {
  65542. return this._dPadRight;
  65543. },
  65544. set: function (value) {
  65545. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  65546. },
  65547. enumerable: true,
  65548. configurable: true
  65549. });
  65550. Xbox360Pad.prototype.update = function () {
  65551. _super.prototype.update.call(this);
  65552. if (this._isXboxOnePad) {
  65553. this.buttonA = this.browserGamepad.buttons[0].value;
  65554. this.buttonB = this.browserGamepad.buttons[1].value;
  65555. this.buttonX = this.browserGamepad.buttons[2].value;
  65556. this.buttonY = this.browserGamepad.buttons[3].value;
  65557. this.buttonLB = this.browserGamepad.buttons[4].value;
  65558. this.buttonRB = this.browserGamepad.buttons[5].value;
  65559. this.leftTrigger = this.browserGamepad.axes[2];
  65560. this.rightTrigger = this.browserGamepad.axes[5];
  65561. this.buttonBack = this.browserGamepad.buttons[9].value;
  65562. this.buttonStart = this.browserGamepad.buttons[8].value;
  65563. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  65564. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  65565. this.dPadUp = this.browserGamepad.buttons[11].value;
  65566. this.dPadDown = this.browserGamepad.buttons[12].value;
  65567. this.dPadLeft = this.browserGamepad.buttons[13].value;
  65568. this.dPadRight = this.browserGamepad.buttons[14].value;
  65569. }
  65570. else {
  65571. this.buttonA = this.browserGamepad.buttons[0].value;
  65572. this.buttonB = this.browserGamepad.buttons[1].value;
  65573. this.buttonX = this.browserGamepad.buttons[2].value;
  65574. this.buttonY = this.browserGamepad.buttons[3].value;
  65575. this.buttonLB = this.browserGamepad.buttons[4].value;
  65576. this.buttonRB = this.browserGamepad.buttons[5].value;
  65577. this.leftTrigger = this.browserGamepad.buttons[6].value;
  65578. this.rightTrigger = this.browserGamepad.buttons[7].value;
  65579. this.buttonBack = this.browserGamepad.buttons[8].value;
  65580. this.buttonStart = this.browserGamepad.buttons[9].value;
  65581. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  65582. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  65583. this.dPadUp = this.browserGamepad.buttons[12].value;
  65584. this.dPadDown = this.browserGamepad.buttons[13].value;
  65585. this.dPadLeft = this.browserGamepad.buttons[14].value;
  65586. this.dPadRight = this.browserGamepad.buttons[15].value;
  65587. }
  65588. };
  65589. Xbox360Pad.prototype.dispose = function () {
  65590. _super.prototype.dispose.call(this);
  65591. this.onButtonDownObservable.clear();
  65592. this.onButtonUpObservable.clear();
  65593. this.onPadDownObservable.clear();
  65594. this.onPadUpObservable.clear();
  65595. };
  65596. return Xbox360Pad;
  65597. }(BABYLON.Gamepad));
  65598. BABYLON.Xbox360Pad = Xbox360Pad;
  65599. })(BABYLON || (BABYLON = {}));
  65600. //# sourceMappingURL=babylon.xboxGamepad.js.map
  65601. "use strict";
  65602. var BABYLON;
  65603. (function (BABYLON) {
  65604. var PoseEnabledControllerType;
  65605. (function (PoseEnabledControllerType) {
  65606. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  65607. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  65608. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  65609. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  65610. /**
  65611. * Google Daydream
  65612. */
  65613. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  65614. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  65615. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  65616. var PoseEnabledControllerHelper = /** @class */ (function () {
  65617. function PoseEnabledControllerHelper() {
  65618. }
  65619. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  65620. // Oculus Touch
  65621. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  65622. return new BABYLON.OculusTouchController(vrGamepad);
  65623. }
  65624. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  65625. return new BABYLON.WindowsMotionController(vrGamepad);
  65626. }
  65627. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  65628. return new BABYLON.ViveController(vrGamepad);
  65629. }
  65630. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  65631. return new BABYLON.GearVRController(vrGamepad);
  65632. }
  65633. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  65634. return new BABYLON.DaydreamController(vrGamepad);
  65635. }
  65636. else {
  65637. return new BABYLON.GenericController(vrGamepad);
  65638. }
  65639. };
  65640. return PoseEnabledControllerHelper;
  65641. }());
  65642. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  65643. var PoseEnabledController = /** @class */ (function (_super) {
  65644. __extends(PoseEnabledController, _super);
  65645. function PoseEnabledController(browserGamepad) {
  65646. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  65647. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  65648. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  65649. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  65650. // Represents device position and rotation in babylon space
  65651. _this.devicePosition = BABYLON.Vector3.Zero();
  65652. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  65653. _this.deviceScaleFactor = 1;
  65654. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  65655. _this._deviceToWorld = BABYLON.Matrix.Identity();
  65656. /**
  65657. * Node to be used when casting a ray from the controller
  65658. */
  65659. _this._pointingPoseNode = null;
  65660. _this._workingMatrix = BABYLON.Matrix.Identity();
  65661. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  65662. _this.controllerType = PoseEnabledControllerType.GENERIC;
  65663. _this.position = BABYLON.Vector3.Zero();
  65664. _this.rotationQuaternion = new BABYLON.Quaternion();
  65665. _this._calculatedPosition = BABYLON.Vector3.Zero();
  65666. _this._calculatedRotation = new BABYLON.Quaternion();
  65667. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  65668. return _this;
  65669. }
  65670. PoseEnabledController.prototype.update = function () {
  65671. _super.prototype.update.call(this);
  65672. var pose = this.browserGamepad.pose;
  65673. this.updateFromDevice(pose);
  65674. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  65675. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  65676. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  65677. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  65678. if (this._mesh) {
  65679. this._mesh.position.copyFrom(this.devicePosition);
  65680. if (this._mesh.rotationQuaternion) {
  65681. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  65682. }
  65683. }
  65684. };
  65685. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  65686. if (poseData) {
  65687. this.rawPose = poseData;
  65688. if (poseData.position) {
  65689. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  65690. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  65691. this._deviceRoomPosition.z *= -1;
  65692. }
  65693. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  65694. this._calculatedPosition.addInPlace(this.position);
  65695. }
  65696. var pose = this.rawPose;
  65697. if (poseData.orientation && pose.orientation) {
  65698. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  65699. if (this._mesh) {
  65700. if (this._mesh.getScene().useRightHandedSystem) {
  65701. this._deviceRoomRotationQuaternion.z *= -1;
  65702. this._deviceRoomRotationQuaternion.w *= -1;
  65703. }
  65704. else {
  65705. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  65706. }
  65707. }
  65708. // if the camera is set, rotate to the camera's rotation
  65709. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  65710. }
  65711. }
  65712. };
  65713. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  65714. if (this._mesh) {
  65715. this._mesh.parent = null;
  65716. }
  65717. this._mesh = mesh;
  65718. if (this._poseControlledCamera) {
  65719. this._mesh.parent = this._poseControlledCamera;
  65720. }
  65721. if (!this._mesh.rotationQuaternion) {
  65722. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  65723. }
  65724. };
  65725. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  65726. this._poseControlledCamera = camera;
  65727. if (this._mesh) {
  65728. this._mesh.parent = this._poseControlledCamera;
  65729. }
  65730. };
  65731. PoseEnabledController.prototype.dispose = function () {
  65732. if (this._mesh) {
  65733. this._mesh.dispose();
  65734. }
  65735. this._mesh = null;
  65736. _super.prototype.dispose.call(this);
  65737. };
  65738. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  65739. get: function () {
  65740. return this._mesh;
  65741. },
  65742. enumerable: true,
  65743. configurable: true
  65744. });
  65745. PoseEnabledController.prototype.getForwardRay = function (length) {
  65746. if (length === void 0) { length = 100; }
  65747. if (!this.mesh) {
  65748. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  65749. }
  65750. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  65751. var origin = m.getTranslation();
  65752. var forward = new BABYLON.Vector3(0, 0, -1);
  65753. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  65754. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  65755. return new BABYLON.Ray(origin, direction, length);
  65756. };
  65757. /**
  65758. * Name of the child mesh that can be used to cast a ray from the controller
  65759. */
  65760. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  65761. return PoseEnabledController;
  65762. }(BABYLON.Gamepad));
  65763. BABYLON.PoseEnabledController = PoseEnabledController;
  65764. })(BABYLON || (BABYLON = {}));
  65765. //# sourceMappingURL=babylon.poseEnabledController.js.map
  65766. "use strict";
  65767. var BABYLON;
  65768. (function (BABYLON) {
  65769. var WebVRController = /** @class */ (function (_super) {
  65770. __extends(WebVRController, _super);
  65771. function WebVRController(vrGamepad) {
  65772. var _this = _super.call(this, vrGamepad) || this;
  65773. // Observables
  65774. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  65775. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  65776. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  65777. _this.onPadStateChangedObservable = new BABYLON.Observable();
  65778. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  65779. _this.pad = { x: 0, y: 0 };
  65780. // avoid GC, store state in a tmp object
  65781. _this._changes = {
  65782. pressChanged: false,
  65783. touchChanged: false,
  65784. valueChanged: false,
  65785. changed: false
  65786. };
  65787. _this._buttons = new Array(vrGamepad.buttons.length);
  65788. _this.hand = vrGamepad.hand;
  65789. return _this;
  65790. }
  65791. WebVRController.prototype.onButtonStateChange = function (callback) {
  65792. this._onButtonStateChange = callback;
  65793. };
  65794. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  65795. get: function () {
  65796. return this._defaultModel;
  65797. },
  65798. enumerable: true,
  65799. configurable: true
  65800. });
  65801. WebVRController.prototype.update = function () {
  65802. _super.prototype.update.call(this);
  65803. for (var index = 0; index < this._buttons.length; index++) {
  65804. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  65805. }
  65806. ;
  65807. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  65808. this.pad.x = this.leftStick.x;
  65809. this.pad.y = this.leftStick.y;
  65810. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  65811. }
  65812. };
  65813. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  65814. if (!newState) {
  65815. newState = {
  65816. pressed: false,
  65817. touched: false,
  65818. value: 0
  65819. };
  65820. }
  65821. if (!currentState) {
  65822. this._buttons[buttonIndex] = {
  65823. pressed: newState.pressed,
  65824. touched: newState.touched,
  65825. value: newState.value
  65826. };
  65827. return;
  65828. }
  65829. this._checkChanges(newState, currentState);
  65830. if (this._changes.changed) {
  65831. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  65832. this._handleButtonChange(buttonIndex, newState, this._changes);
  65833. }
  65834. this._buttons[buttonIndex].pressed = newState.pressed;
  65835. this._buttons[buttonIndex].touched = newState.touched;
  65836. // oculus triggers are never 0, thou not touched.
  65837. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  65838. };
  65839. WebVRController.prototype._checkChanges = function (newState, currentState) {
  65840. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  65841. this._changes.touchChanged = newState.touched !== currentState.touched;
  65842. this._changes.valueChanged = newState.value !== currentState.value;
  65843. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  65844. return this._changes;
  65845. };
  65846. WebVRController.prototype.dispose = function () {
  65847. _super.prototype.dispose.call(this);
  65848. this.onTriggerStateChangedObservable.clear();
  65849. this.onMainButtonStateChangedObservable.clear();
  65850. this.onSecondaryButtonStateChangedObservable.clear();
  65851. this.onPadStateChangedObservable.clear();
  65852. this.onPadValuesChangedObservable.clear();
  65853. };
  65854. return WebVRController;
  65855. }(BABYLON.PoseEnabledController));
  65856. BABYLON.WebVRController = WebVRController;
  65857. })(BABYLON || (BABYLON = {}));
  65858. //# sourceMappingURL=babylon.webVRController.js.map
  65859. "use strict";
  65860. var BABYLON;
  65861. (function (BABYLON) {
  65862. var OculusTouchController = /** @class */ (function (_super) {
  65863. __extends(OculusTouchController, _super);
  65864. function OculusTouchController(vrGamepad) {
  65865. var _this = _super.call(this, vrGamepad) || this;
  65866. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  65867. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  65868. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  65869. return _this;
  65870. }
  65871. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65872. var _this = this;
  65873. var meshName;
  65874. // Hand
  65875. if (this.hand === 'left') {
  65876. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  65877. }
  65878. else {
  65879. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  65880. }
  65881. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  65882. /*
  65883. Parent Mesh name: oculus_touch_left
  65884. - body
  65885. - trigger
  65886. - thumbstick
  65887. - grip
  65888. - button_y
  65889. - button_x
  65890. - button_enter
  65891. */
  65892. _this._defaultModel = newMeshes[1];
  65893. _this.attachToMesh(_this._defaultModel);
  65894. if (meshLoaded) {
  65895. meshLoaded(_this._defaultModel);
  65896. }
  65897. });
  65898. };
  65899. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  65900. // helper getters for left and right hand.
  65901. get: function () {
  65902. if (this.hand === 'right') {
  65903. return this.onMainButtonStateChangedObservable;
  65904. }
  65905. else {
  65906. throw new Error('No A button on left hand');
  65907. }
  65908. },
  65909. enumerable: true,
  65910. configurable: true
  65911. });
  65912. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  65913. get: function () {
  65914. if (this.hand === 'right') {
  65915. return this.onSecondaryButtonStateChangedObservable;
  65916. }
  65917. else {
  65918. throw new Error('No B button on left hand');
  65919. }
  65920. },
  65921. enumerable: true,
  65922. configurable: true
  65923. });
  65924. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  65925. get: function () {
  65926. if (this.hand === 'left') {
  65927. return this.onMainButtonStateChangedObservable;
  65928. }
  65929. else {
  65930. throw new Error('No X button on right hand');
  65931. }
  65932. },
  65933. enumerable: true,
  65934. configurable: true
  65935. });
  65936. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  65937. get: function () {
  65938. if (this.hand === 'left') {
  65939. return this.onSecondaryButtonStateChangedObservable;
  65940. }
  65941. else {
  65942. throw new Error('No Y button on right hand');
  65943. }
  65944. },
  65945. enumerable: true,
  65946. configurable: true
  65947. });
  65948. /*
  65949. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  65950. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  65951. 2) secondary trigger (same)
  65952. 3) A (right) X (left), touch, pressed = value
  65953. 4) B / Y
  65954. 5) thumb rest
  65955. */
  65956. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65957. var notifyObject = state; //{ state: state, changes: changes };
  65958. var triggerDirection = this.hand === 'right' ? -1 : 1;
  65959. switch (buttonIdx) {
  65960. case 0:
  65961. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  65962. return;
  65963. case 1:// index trigger
  65964. if (this._defaultModel) {
  65965. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  65966. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  65967. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  65968. }
  65969. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  65970. return;
  65971. case 2:// secondary trigger
  65972. if (this._defaultModel) {
  65973. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  65974. }
  65975. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  65976. return;
  65977. case 3:
  65978. if (this._defaultModel) {
  65979. if (notifyObject.pressed) {
  65980. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  65981. }
  65982. else {
  65983. (this._defaultModel.getChildren()[1]).position.y = 0;
  65984. }
  65985. }
  65986. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  65987. return;
  65988. case 4:
  65989. if (this._defaultModel) {
  65990. if (notifyObject.pressed) {
  65991. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  65992. }
  65993. else {
  65994. (this._defaultModel.getChildren()[2]).position.y = 0;
  65995. }
  65996. }
  65997. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  65998. return;
  65999. case 5:
  66000. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  66001. return;
  66002. }
  66003. };
  66004. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  66005. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  66006. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  66007. return OculusTouchController;
  66008. }(BABYLON.WebVRController));
  66009. BABYLON.OculusTouchController = OculusTouchController;
  66010. })(BABYLON || (BABYLON = {}));
  66011. //# sourceMappingURL=babylon.oculusTouchController.js.map
  66012. "use strict";
  66013. var BABYLON;
  66014. (function (BABYLON) {
  66015. var ViveController = /** @class */ (function (_super) {
  66016. __extends(ViveController, _super);
  66017. function ViveController(vrGamepad) {
  66018. var _this = _super.call(this, vrGamepad) || this;
  66019. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  66020. _this._invertLeftStickY = true;
  66021. return _this;
  66022. }
  66023. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66024. var _this = this;
  66025. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  66026. /*
  66027. Parent Mesh name: ViveWand
  66028. - body
  66029. - r_gripper
  66030. - l_gripper
  66031. - menu_button
  66032. - system_button
  66033. - trackpad
  66034. - trigger
  66035. - LED
  66036. */
  66037. _this._defaultModel = newMeshes[1];
  66038. _this.attachToMesh(_this._defaultModel);
  66039. if (meshLoaded) {
  66040. meshLoaded(_this._defaultModel);
  66041. }
  66042. });
  66043. };
  66044. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  66045. get: function () {
  66046. return this.onMainButtonStateChangedObservable;
  66047. },
  66048. enumerable: true,
  66049. configurable: true
  66050. });
  66051. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  66052. get: function () {
  66053. return this.onMainButtonStateChangedObservable;
  66054. },
  66055. enumerable: true,
  66056. configurable: true
  66057. });
  66058. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  66059. get: function () {
  66060. return this.onSecondaryButtonStateChangedObservable;
  66061. },
  66062. enumerable: true,
  66063. configurable: true
  66064. });
  66065. /**
  66066. * Vive mapping:
  66067. * 0: touchpad
  66068. * 1: trigger
  66069. * 2: left AND right buttons
  66070. * 3: menu button
  66071. */
  66072. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66073. var notifyObject = state; //{ state: state, changes: changes };
  66074. switch (buttonIdx) {
  66075. case 0:
  66076. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  66077. return;
  66078. case 1:// index trigger
  66079. if (this._defaultModel) {
  66080. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  66081. }
  66082. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  66083. return;
  66084. case 2:// left AND right button
  66085. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  66086. return;
  66087. case 3:
  66088. if (this._defaultModel) {
  66089. if (notifyObject.pressed) {
  66090. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  66091. }
  66092. else {
  66093. (this._defaultModel.getChildren()[2]).position.y = 0;
  66094. }
  66095. }
  66096. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  66097. return;
  66098. }
  66099. };
  66100. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  66101. ViveController.MODEL_FILENAME = 'wand.babylon';
  66102. return ViveController;
  66103. }(BABYLON.WebVRController));
  66104. BABYLON.ViveController = ViveController;
  66105. })(BABYLON || (BABYLON = {}));
  66106. //# sourceMappingURL=babylon.viveController.js.map
  66107. "use strict";
  66108. var BABYLON;
  66109. (function (BABYLON) {
  66110. var GenericController = /** @class */ (function (_super) {
  66111. __extends(GenericController, _super);
  66112. function GenericController(vrGamepad) {
  66113. return _super.call(this, vrGamepad) || this;
  66114. }
  66115. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66116. var _this = this;
  66117. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  66118. _this._defaultModel = newMeshes[1];
  66119. _this.attachToMesh(_this._defaultModel);
  66120. if (meshLoaded) {
  66121. meshLoaded(_this._defaultModel);
  66122. }
  66123. });
  66124. };
  66125. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66126. console.log("Button id: " + buttonIdx + "state: ");
  66127. console.dir(state);
  66128. };
  66129. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66130. GenericController.MODEL_FILENAME = 'generic.babylon';
  66131. return GenericController;
  66132. }(BABYLON.WebVRController));
  66133. BABYLON.GenericController = GenericController;
  66134. })(BABYLON || (BABYLON = {}));
  66135. //# sourceMappingURL=babylon.genericController.js.map
  66136. "use strict";
  66137. var BABYLON;
  66138. (function (BABYLON) {
  66139. var LoadedMeshInfo = /** @class */ (function () {
  66140. function LoadedMeshInfo() {
  66141. this.buttonMeshes = {};
  66142. this.axisMeshes = {};
  66143. }
  66144. return LoadedMeshInfo;
  66145. }());
  66146. var WindowsMotionController = /** @class */ (function (_super) {
  66147. __extends(WindowsMotionController, _super);
  66148. function WindowsMotionController(vrGamepad) {
  66149. var _this = _super.call(this, vrGamepad) || this;
  66150. _this._mapping = {
  66151. // Semantic button names
  66152. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  66153. // A mapping of the button name to glTF model node name
  66154. // that should be transformed by button value.
  66155. buttonMeshNames: {
  66156. 'trigger': 'SELECT',
  66157. 'menu': 'MENU',
  66158. 'grip': 'GRASP',
  66159. 'thumbstick': 'THUMBSTICK_PRESS',
  66160. 'trackpad': 'TOUCHPAD_PRESS'
  66161. },
  66162. // This mapping is used to translate from the Motion Controller to Babylon semantics
  66163. buttonObservableNames: {
  66164. 'trigger': 'onTriggerStateChangedObservable',
  66165. 'menu': 'onSecondaryButtonStateChangedObservable',
  66166. 'grip': 'onMainButtonStateChangedObservable',
  66167. 'thumbstick': 'onPadStateChangedObservable',
  66168. 'trackpad': 'onTrackpadChangedObservable'
  66169. },
  66170. // A mapping of the axis name to glTF model node name
  66171. // that should be transformed by axis value.
  66172. // This array mirrors the browserGamepad.axes array, such that
  66173. // the mesh corresponding to axis 0 is in this array index 0.
  66174. axisMeshNames: [
  66175. 'THUMBSTICK_X',
  66176. 'THUMBSTICK_Y',
  66177. 'TOUCHPAD_TOUCH_X',
  66178. 'TOUCHPAD_TOUCH_Y'
  66179. ],
  66180. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  66181. };
  66182. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  66183. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  66184. _this.trackpad = { x: 0, y: 0 };
  66185. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  66186. _this._loadedMeshInfo = null;
  66187. return _this;
  66188. }
  66189. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  66190. get: function () {
  66191. return this.onTriggerStateChangedObservable;
  66192. },
  66193. enumerable: true,
  66194. configurable: true
  66195. });
  66196. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  66197. get: function () {
  66198. return this.onSecondaryButtonStateChangedObservable;
  66199. },
  66200. enumerable: true,
  66201. configurable: true
  66202. });
  66203. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  66204. get: function () {
  66205. return this.onMainButtonStateChangedObservable;
  66206. },
  66207. enumerable: true,
  66208. configurable: true
  66209. });
  66210. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  66211. get: function () {
  66212. return this.onPadStateChangedObservable;
  66213. },
  66214. enumerable: true,
  66215. configurable: true
  66216. });
  66217. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  66218. get: function () {
  66219. return this.onTrackpadChangedObservable;
  66220. },
  66221. enumerable: true,
  66222. configurable: true
  66223. });
  66224. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  66225. get: function () {
  66226. return this.onTrackpadValuesChangedObservable;
  66227. },
  66228. enumerable: true,
  66229. configurable: true
  66230. });
  66231. /**
  66232. * Called once per frame by the engine.
  66233. */
  66234. WindowsMotionController.prototype.update = function () {
  66235. _super.prototype.update.call(this);
  66236. if (this.browserGamepad.axes) {
  66237. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  66238. this.trackpad.x = this.browserGamepad["axes"][2];
  66239. this.trackpad.y = this.browserGamepad["axes"][3];
  66240. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  66241. }
  66242. // Only need to animate axes if there is a loaded mesh
  66243. if (this._loadedMeshInfo) {
  66244. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  66245. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  66246. }
  66247. }
  66248. }
  66249. };
  66250. /**
  66251. * Called once for each button that changed state since the last frame
  66252. * @param buttonIdx Which button index changed
  66253. * @param state New state of the button
  66254. * @param changes Which properties on the state changed since last frame
  66255. */
  66256. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66257. var buttonName = this._mapping.buttons[buttonIdx];
  66258. if (!buttonName) {
  66259. return;
  66260. }
  66261. // Only emit events for buttons that we know how to map from index to name
  66262. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  66263. if (observable) {
  66264. observable.notifyObservers(state);
  66265. }
  66266. this.lerpButtonTransform(buttonName, state.value);
  66267. };
  66268. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  66269. // If there is no loaded mesh, there is nothing to transform.
  66270. if (!this._loadedMeshInfo) {
  66271. return;
  66272. }
  66273. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  66274. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  66275. return;
  66276. }
  66277. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  66278. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  66279. };
  66280. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  66281. if (!this._loadedMeshInfo) {
  66282. return;
  66283. }
  66284. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  66285. if (!meshInfo) {
  66286. return;
  66287. }
  66288. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  66289. return;
  66290. }
  66291. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  66292. var lerpValue = axisValue * 0.5 + 0.5;
  66293. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  66294. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  66295. };
  66296. /**
  66297. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  66298. * @param scene scene in which to add meshes
  66299. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  66300. */
  66301. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  66302. var _this = this;
  66303. if (forceDefault === void 0) { forceDefault = false; }
  66304. var path;
  66305. var filename;
  66306. // Checking if GLB loader is present
  66307. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  66308. // Determine the device specific folder based on the ID suffix
  66309. var device = 'default';
  66310. if (this.id && !forceDefault) {
  66311. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  66312. device = ((match && match[0]) || device);
  66313. }
  66314. // Hand
  66315. if (this.hand === 'left') {
  66316. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  66317. }
  66318. else {
  66319. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  66320. }
  66321. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  66322. }
  66323. else {
  66324. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  66325. path = BABYLON.GenericController.MODEL_BASE_URL;
  66326. filename = BABYLON.GenericController.MODEL_FILENAME;
  66327. }
  66328. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  66329. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  66330. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  66331. if (!_this._loadedMeshInfo) {
  66332. return;
  66333. }
  66334. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  66335. _this.attachToMesh(_this._defaultModel);
  66336. if (meshLoaded) {
  66337. meshLoaded(_this._defaultModel);
  66338. }
  66339. }, null, function (scene, message) {
  66340. BABYLON.Tools.Log(message);
  66341. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  66342. if (!forceDefault) {
  66343. _this.initControllerMesh(scene, meshLoaded, true);
  66344. }
  66345. });
  66346. };
  66347. /**
  66348. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  66349. * can be transformed by button presses and axes values, based on this._mapping.
  66350. *
  66351. * @param scene scene in which the meshes exist
  66352. * @param meshes list of meshes that make up the controller model to process
  66353. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  66354. */
  66355. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  66356. var loadedMeshInfo = null;
  66357. // Create a new mesh to contain the glTF hierarchy
  66358. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  66359. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  66360. var childMesh = null;
  66361. for (var i = 0; i < meshes.length; i++) {
  66362. var mesh = meshes[i];
  66363. if (!mesh.parent) {
  66364. // Exclude controller meshes from picking results
  66365. mesh.isPickable = false;
  66366. // Handle root node, attach to the new parentMesh
  66367. childMesh = mesh;
  66368. break;
  66369. }
  66370. }
  66371. if (childMesh) {
  66372. childMesh.setParent(parentMesh);
  66373. // Create our mesh info. Note that this method will always return non-null.
  66374. loadedMeshInfo = this.createMeshInfo(parentMesh);
  66375. }
  66376. else {
  66377. BABYLON.Tools.Warn('Could not find root node in model file.');
  66378. }
  66379. return loadedMeshInfo;
  66380. };
  66381. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  66382. var loadedMeshInfo = new LoadedMeshInfo();
  66383. var i;
  66384. loadedMeshInfo.rootNode = rootNode;
  66385. // Reset the caches
  66386. loadedMeshInfo.buttonMeshes = {};
  66387. loadedMeshInfo.axisMeshes = {};
  66388. // Button Meshes
  66389. for (i = 0; i < this._mapping.buttons.length; i++) {
  66390. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  66391. if (!buttonMeshName) {
  66392. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  66393. continue;
  66394. }
  66395. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  66396. if (!buttonMesh) {
  66397. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  66398. continue;
  66399. }
  66400. var buttonMeshInfo = {
  66401. index: i,
  66402. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  66403. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  66404. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  66405. };
  66406. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  66407. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  66408. }
  66409. else {
  66410. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  66411. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  66412. '(VALUE: ' + !!buttonMeshInfo.value +
  66413. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  66414. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  66415. ')');
  66416. }
  66417. }
  66418. // Axis Meshes
  66419. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  66420. var axisMeshName = this._mapping.axisMeshNames[i];
  66421. if (!axisMeshName) {
  66422. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  66423. continue;
  66424. }
  66425. var axisMesh = getChildByName(rootNode, axisMeshName);
  66426. if (!axisMesh) {
  66427. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  66428. continue;
  66429. }
  66430. var axisMeshInfo = {
  66431. index: i,
  66432. value: getImmediateChildByName(axisMesh, 'VALUE'),
  66433. min: getImmediateChildByName(axisMesh, 'MIN'),
  66434. max: getImmediateChildByName(axisMesh, 'MAX')
  66435. };
  66436. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  66437. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  66438. }
  66439. else {
  66440. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  66441. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  66442. '(VALUE: ' + !!axisMeshInfo.value +
  66443. ', MIN: ' + !!axisMeshInfo.min +
  66444. ', MAX:' + !!axisMeshInfo.max +
  66445. ')');
  66446. }
  66447. }
  66448. // Pointing Ray
  66449. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  66450. if (!loadedMeshInfo.pointingPoseNode) {
  66451. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  66452. }
  66453. return loadedMeshInfo;
  66454. // Look through all children recursively. This will return null if no mesh exists with the given name.
  66455. function getChildByName(node, name) {
  66456. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  66457. }
  66458. // Look through only immediate children. This will return null if no mesh exists with the given name.
  66459. function getImmediateChildByName(node, name) {
  66460. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  66461. }
  66462. };
  66463. WindowsMotionController.prototype.getForwardRay = function (length) {
  66464. if (length === void 0) { length = 100; }
  66465. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  66466. return _super.prototype.getForwardRay.call(this, length);
  66467. }
  66468. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  66469. var origin = m.getTranslation();
  66470. var forward = new BABYLON.Vector3(0, 0, -1);
  66471. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  66472. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  66473. return new BABYLON.Ray(origin, direction, length);
  66474. };
  66475. WindowsMotionController.prototype.dispose = function () {
  66476. _super.prototype.dispose.call(this);
  66477. this.onTrackpadChangedObservable.clear();
  66478. };
  66479. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  66480. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  66481. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  66482. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  66483. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  66484. return WindowsMotionController;
  66485. }(BABYLON.WebVRController));
  66486. BABYLON.WindowsMotionController = WindowsMotionController;
  66487. })(BABYLON || (BABYLON = {}));
  66488. //# sourceMappingURL=babylon.windowsMotionController.js.map
  66489. "use strict";
  66490. var BABYLON;
  66491. (function (BABYLON) {
  66492. var GearVRController = /** @class */ (function (_super) {
  66493. __extends(GearVRController, _super);
  66494. function GearVRController(vrGamepad) {
  66495. var _this = _super.call(this, vrGamepad) || this;
  66496. _this._buttonIndexToObservableNameMap = [
  66497. 'onTrackpadChangedObservable',
  66498. 'onTriggerStateChangedObservable' // Trigger
  66499. ];
  66500. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  66501. return _this;
  66502. }
  66503. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66504. var _this = this;
  66505. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  66506. _this._defaultModel = newMeshes[1];
  66507. _this.attachToMesh(_this._defaultModel);
  66508. if (meshLoaded) {
  66509. meshLoaded(_this._defaultModel);
  66510. }
  66511. });
  66512. };
  66513. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66514. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  66515. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  66516. // Only emit events for buttons that we know how to map from index to observable
  66517. var observable = this[observableName];
  66518. if (observable) {
  66519. observable.notifyObservers(state);
  66520. }
  66521. }
  66522. };
  66523. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66524. GearVRController.MODEL_FILENAME = 'generic.babylon';
  66525. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  66526. return GearVRController;
  66527. }(BABYLON.WebVRController));
  66528. BABYLON.GearVRController = GearVRController;
  66529. })(BABYLON || (BABYLON = {}));
  66530. //# sourceMappingURL=babylon.gearVRController.js.map
  66531. "use strict";
  66532. var BABYLON;
  66533. (function (BABYLON) {
  66534. /**
  66535. * Google Daydream controller
  66536. */
  66537. var DaydreamController = /** @class */ (function (_super) {
  66538. __extends(DaydreamController, _super);
  66539. function DaydreamController(vrGamepad) {
  66540. var _this = _super.call(this, vrGamepad) || this;
  66541. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  66542. return _this;
  66543. }
  66544. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66545. var _this = this;
  66546. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  66547. _this._defaultModel = newMeshes[1];
  66548. _this.attachToMesh(_this._defaultModel);
  66549. if (meshLoaded) {
  66550. meshLoaded(_this._defaultModel);
  66551. }
  66552. });
  66553. };
  66554. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66555. // Daydream controller only has 1 GamepadButton (on the trackpad).
  66556. if (buttonIdx === 0) {
  66557. var observable = this.onTriggerStateChangedObservable;
  66558. if (observable) {
  66559. observable.notifyObservers(state);
  66560. }
  66561. }
  66562. else {
  66563. // If the app or home buttons are ever made available
  66564. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  66565. }
  66566. };
  66567. /**
  66568. * Base Url for the controller model.
  66569. */
  66570. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66571. /**
  66572. * File name for the controller model.
  66573. */
  66574. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  66575. /**
  66576. * Gamepad Id prefix used to identify Daydream Controller.
  66577. */
  66578. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  66579. return DaydreamController;
  66580. }(BABYLON.WebVRController));
  66581. BABYLON.DaydreamController = DaydreamController;
  66582. })(BABYLON || (BABYLON = {}));
  66583. //# sourceMappingURL=babylon.daydreamController.js.map
  66584. "use strict";
  66585. var BABYLON;
  66586. (function (BABYLON) {
  66587. var FollowCamera = /** @class */ (function (_super) {
  66588. __extends(FollowCamera, _super);
  66589. function FollowCamera(name, position, scene, lockedTarget) {
  66590. if (lockedTarget === void 0) { lockedTarget = null; }
  66591. var _this = _super.call(this, name, position, scene) || this;
  66592. _this.radius = 12;
  66593. _this.rotationOffset = 0;
  66594. _this.heightOffset = 4;
  66595. _this.cameraAcceleration = 0.05;
  66596. _this.maxCameraSpeed = 20;
  66597. _this.lockedTarget = lockedTarget;
  66598. return _this;
  66599. }
  66600. FollowCamera.prototype.getRadians = function (degrees) {
  66601. return degrees * Math.PI / 180;
  66602. };
  66603. FollowCamera.prototype.follow = function (cameraTarget) {
  66604. if (!cameraTarget)
  66605. return;
  66606. var yRotation;
  66607. if (cameraTarget.rotationQuaternion) {
  66608. var rotMatrix = new BABYLON.Matrix();
  66609. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  66610. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  66611. }
  66612. else {
  66613. yRotation = cameraTarget.rotation.y;
  66614. }
  66615. var radians = this.getRadians(this.rotationOffset) + yRotation;
  66616. var targetPosition = cameraTarget.getAbsolutePosition();
  66617. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  66618. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  66619. var dx = targetX - this.position.x;
  66620. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  66621. var dz = (targetZ) - this.position.z;
  66622. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  66623. var vy = dy * this.cameraAcceleration;
  66624. var vz = dz * this.cameraAcceleration * 2;
  66625. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  66626. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66627. }
  66628. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  66629. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66630. }
  66631. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  66632. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66633. }
  66634. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  66635. this.setTarget(targetPosition);
  66636. };
  66637. FollowCamera.prototype._checkInputs = function () {
  66638. _super.prototype._checkInputs.call(this);
  66639. if (this.lockedTarget) {
  66640. this.follow(this.lockedTarget);
  66641. }
  66642. };
  66643. FollowCamera.prototype.getClassName = function () {
  66644. return "FollowCamera";
  66645. };
  66646. __decorate([
  66647. BABYLON.serialize()
  66648. ], FollowCamera.prototype, "radius", void 0);
  66649. __decorate([
  66650. BABYLON.serialize()
  66651. ], FollowCamera.prototype, "rotationOffset", void 0);
  66652. __decorate([
  66653. BABYLON.serialize()
  66654. ], FollowCamera.prototype, "heightOffset", void 0);
  66655. __decorate([
  66656. BABYLON.serialize()
  66657. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  66658. __decorate([
  66659. BABYLON.serialize()
  66660. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  66661. __decorate([
  66662. BABYLON.serializeAsMeshReference("lockedTargetId")
  66663. ], FollowCamera.prototype, "lockedTarget", void 0);
  66664. return FollowCamera;
  66665. }(BABYLON.TargetCamera));
  66666. BABYLON.FollowCamera = FollowCamera;
  66667. var ArcFollowCamera = /** @class */ (function (_super) {
  66668. __extends(ArcFollowCamera, _super);
  66669. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  66670. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  66671. _this.alpha = alpha;
  66672. _this.beta = beta;
  66673. _this.radius = radius;
  66674. _this.target = target;
  66675. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  66676. _this.follow();
  66677. return _this;
  66678. }
  66679. ArcFollowCamera.prototype.follow = function () {
  66680. if (!this.target) {
  66681. return;
  66682. }
  66683. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  66684. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  66685. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  66686. var targetPosition = this.target.getAbsolutePosition();
  66687. this.position = targetPosition.add(this._cartesianCoordinates);
  66688. this.setTarget(targetPosition);
  66689. };
  66690. ArcFollowCamera.prototype._checkInputs = function () {
  66691. _super.prototype._checkInputs.call(this);
  66692. this.follow();
  66693. };
  66694. ArcFollowCamera.prototype.getClassName = function () {
  66695. return "ArcFollowCamera";
  66696. };
  66697. return ArcFollowCamera;
  66698. }(BABYLON.TargetCamera));
  66699. BABYLON.ArcFollowCamera = ArcFollowCamera;
  66700. })(BABYLON || (BABYLON = {}));
  66701. //# sourceMappingURL=babylon.followCamera.js.map
  66702. "use strict";
  66703. var BABYLON;
  66704. (function (BABYLON) {
  66705. // We're mainly based on the logic defined into the FreeCamera code
  66706. var UniversalCamera = /** @class */ (function (_super) {
  66707. __extends(UniversalCamera, _super);
  66708. //-- end properties for backward compatibility for inputs
  66709. function UniversalCamera(name, position, scene) {
  66710. var _this = _super.call(this, name, position, scene) || this;
  66711. _this.inputs.addGamepad();
  66712. return _this;
  66713. }
  66714. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  66715. //-- Begin properties for backward compatibility for inputs
  66716. get: function () {
  66717. var gamepad = this.inputs.attached["gamepad"];
  66718. if (gamepad)
  66719. return gamepad.gamepadAngularSensibility;
  66720. return 0;
  66721. },
  66722. set: function (value) {
  66723. var gamepad = this.inputs.attached["gamepad"];
  66724. if (gamepad)
  66725. gamepad.gamepadAngularSensibility = value;
  66726. },
  66727. enumerable: true,
  66728. configurable: true
  66729. });
  66730. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  66731. get: function () {
  66732. var gamepad = this.inputs.attached["gamepad"];
  66733. if (gamepad)
  66734. return gamepad.gamepadMoveSensibility;
  66735. return 0;
  66736. },
  66737. set: function (value) {
  66738. var gamepad = this.inputs.attached["gamepad"];
  66739. if (gamepad)
  66740. gamepad.gamepadMoveSensibility = value;
  66741. },
  66742. enumerable: true,
  66743. configurable: true
  66744. });
  66745. UniversalCamera.prototype.getClassName = function () {
  66746. return "UniversalCamera";
  66747. };
  66748. return UniversalCamera;
  66749. }(BABYLON.TouchCamera));
  66750. BABYLON.UniversalCamera = UniversalCamera;
  66751. })(BABYLON || (BABYLON = {}));
  66752. //# sourceMappingURL=babylon.universalCamera.js.map
  66753. "use strict";
  66754. var BABYLON;
  66755. (function (BABYLON) {
  66756. // We're mainly based on the logic defined into the FreeCamera code
  66757. var GamepadCamera = /** @class */ (function (_super) {
  66758. __extends(GamepadCamera, _super);
  66759. //-- end properties for backward compatibility for inputs
  66760. function GamepadCamera(name, position, scene) {
  66761. return _super.call(this, name, position, scene) || this;
  66762. }
  66763. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  66764. //-- Begin properties for backward compatibility for inputs
  66765. get: function () {
  66766. var gamepad = this.inputs.attached["gamepad"];
  66767. if (gamepad)
  66768. return gamepad.gamepadAngularSensibility;
  66769. return 0;
  66770. },
  66771. set: function (value) {
  66772. var gamepad = this.inputs.attached["gamepad"];
  66773. if (gamepad)
  66774. gamepad.gamepadAngularSensibility = value;
  66775. },
  66776. enumerable: true,
  66777. configurable: true
  66778. });
  66779. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  66780. get: function () {
  66781. var gamepad = this.inputs.attached["gamepad"];
  66782. if (gamepad)
  66783. return gamepad.gamepadMoveSensibility;
  66784. return 0;
  66785. },
  66786. set: function (value) {
  66787. var gamepad = this.inputs.attached["gamepad"];
  66788. if (gamepad)
  66789. gamepad.gamepadMoveSensibility = value;
  66790. },
  66791. enumerable: true,
  66792. configurable: true
  66793. });
  66794. GamepadCamera.prototype.getClassName = function () {
  66795. return "GamepadCamera";
  66796. };
  66797. return GamepadCamera;
  66798. }(BABYLON.UniversalCamera));
  66799. BABYLON.GamepadCamera = GamepadCamera;
  66800. })(BABYLON || (BABYLON = {}));
  66801. //# sourceMappingURL=babylon.gamepadCamera.js.map
  66802. "use strict";
  66803. var BABYLON;
  66804. (function (BABYLON) {
  66805. var PostProcessRenderPipelineManager = /** @class */ (function () {
  66806. function PostProcessRenderPipelineManager() {
  66807. this._renderPipelines = {};
  66808. }
  66809. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  66810. this._renderPipelines[renderPipeline._name] = renderPipeline;
  66811. };
  66812. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  66813. if (unique === void 0) { unique = false; }
  66814. var renderPipeline = this._renderPipelines[renderPipelineName];
  66815. if (!renderPipeline) {
  66816. return;
  66817. }
  66818. renderPipeline._attachCameras(cameras, unique);
  66819. };
  66820. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  66821. var renderPipeline = this._renderPipelines[renderPipelineName];
  66822. if (!renderPipeline) {
  66823. return;
  66824. }
  66825. renderPipeline._detachCameras(cameras);
  66826. };
  66827. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  66828. var renderPipeline = this._renderPipelines[renderPipelineName];
  66829. if (!renderPipeline) {
  66830. return;
  66831. }
  66832. renderPipeline._enableEffect(renderEffectName, cameras);
  66833. };
  66834. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  66835. var renderPipeline = this._renderPipelines[renderPipelineName];
  66836. if (!renderPipeline) {
  66837. return;
  66838. }
  66839. renderPipeline._disableEffect(renderEffectName, cameras);
  66840. };
  66841. PostProcessRenderPipelineManager.prototype.update = function () {
  66842. for (var renderPipelineName in this._renderPipelines) {
  66843. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66844. var pipeline = this._renderPipelines[renderPipelineName];
  66845. if (!pipeline.isSupported) {
  66846. pipeline.dispose();
  66847. delete this._renderPipelines[renderPipelineName];
  66848. }
  66849. else {
  66850. pipeline._update();
  66851. }
  66852. }
  66853. }
  66854. };
  66855. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  66856. for (var renderPipelineName in this._renderPipelines) {
  66857. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66858. var pipeline = this._renderPipelines[renderPipelineName];
  66859. pipeline._rebuild();
  66860. }
  66861. }
  66862. };
  66863. PostProcessRenderPipelineManager.prototype.dispose = function () {
  66864. for (var renderPipelineName in this._renderPipelines) {
  66865. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66866. var pipeline = this._renderPipelines[renderPipelineName];
  66867. pipeline.dispose();
  66868. }
  66869. }
  66870. };
  66871. return PostProcessRenderPipelineManager;
  66872. }());
  66873. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  66874. })(BABYLON || (BABYLON = {}));
  66875. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  66876. "use strict";
  66877. var BABYLON;
  66878. (function (BABYLON) {
  66879. /**
  66880. * This represents a set of one or more post processes in Babylon.
  66881. * A post process can be used to apply a shader to a texture after it is rendered.
  66882. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  66883. */
  66884. var PostProcessRenderEffect = /** @class */ (function () {
  66885. /**
  66886. * Instantiates a post process render effect.
  66887. * A post process can be used to apply a shader to a texture after it is rendered.
  66888. * @param engine The engine the effect is tied to
  66889. * @param name The name of the effect
  66890. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  66891. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  66892. */
  66893. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  66894. this._name = name;
  66895. this._singleInstance = singleInstance || true;
  66896. this._getPostProcesses = getPostProcesses;
  66897. this._cameras = {};
  66898. this._indicesForCamera = {};
  66899. this._postProcesses = {};
  66900. }
  66901. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  66902. /**
  66903. * Checks if all the post processes in the effect are supported.
  66904. */
  66905. get: function () {
  66906. for (var index in this._postProcesses) {
  66907. for (var ppIndex in this._postProcesses[index]) {
  66908. if (!this._postProcesses[index][ppIndex].isSupported) {
  66909. return false;
  66910. }
  66911. }
  66912. }
  66913. return true;
  66914. },
  66915. enumerable: true,
  66916. configurable: true
  66917. });
  66918. /**
  66919. * Updates the current state of the effect
  66920. */
  66921. PostProcessRenderEffect.prototype._update = function () {
  66922. };
  66923. /**
  66924. * Attaches the effect on cameras
  66925. * @param cameras The camera to attach to.
  66926. */
  66927. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  66928. var _this = this;
  66929. var cameraKey;
  66930. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66931. if (!cams) {
  66932. return;
  66933. }
  66934. for (var i = 0; i < cams.length; i++) {
  66935. var camera = cams[i];
  66936. var cameraName = camera.name;
  66937. if (this._singleInstance) {
  66938. cameraKey = 0;
  66939. }
  66940. else {
  66941. cameraKey = cameraName;
  66942. }
  66943. if (!this._postProcesses[cameraKey]) {
  66944. var postProcess = this._getPostProcesses();
  66945. if (postProcess) {
  66946. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  66947. }
  66948. }
  66949. if (!this._indicesForCamera[cameraName]) {
  66950. this._indicesForCamera[cameraName] = [];
  66951. }
  66952. this._postProcesses[cameraKey].forEach(function (postProcess) {
  66953. var index = camera.attachPostProcess(postProcess);
  66954. _this._indicesForCamera[cameraName].push(index);
  66955. });
  66956. if (!this._cameras[cameraName]) {
  66957. this._cameras[cameraName] = camera;
  66958. }
  66959. }
  66960. };
  66961. /**
  66962. * Detatches the effect on cameras
  66963. * @param cameras The camera to detatch from.
  66964. */
  66965. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  66966. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66967. if (!cams) {
  66968. return;
  66969. }
  66970. for (var i = 0; i < cams.length; i++) {
  66971. var camera = cams[i];
  66972. var cameraName = camera.name;
  66973. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66974. camera.detachPostProcess(postProcess);
  66975. });
  66976. if (this._cameras[cameraName]) {
  66977. //this._indicesForCamera.splice(index, 1);
  66978. this._cameras[cameraName] = null;
  66979. }
  66980. }
  66981. };
  66982. /**
  66983. * Enables the effect on given cameras
  66984. * @param cameras The camera to enable.
  66985. */
  66986. PostProcessRenderEffect.prototype._enable = function (cameras) {
  66987. var _this = this;
  66988. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66989. if (!cams) {
  66990. return;
  66991. }
  66992. for (var i = 0; i < cams.length; i++) {
  66993. var camera = cams[i];
  66994. var cameraName = camera.name;
  66995. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  66996. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  66997. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66998. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  66999. });
  67000. }
  67001. }
  67002. }
  67003. };
  67004. /**
  67005. * Disables the effect on the given cameras
  67006. * @param cameras The camera to disable.
  67007. */
  67008. PostProcessRenderEffect.prototype._disable = function (cameras) {
  67009. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67010. if (!cams) {
  67011. return;
  67012. }
  67013. for (var i = 0; i < cams.length; i++) {
  67014. var camera = cams[i];
  67015. var cameraName = camera.name;
  67016. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67017. camera.detachPostProcess(postProcess);
  67018. });
  67019. }
  67020. };
  67021. /**
  67022. * Gets a list of the post processes contained in the effect.
  67023. * @param camera The camera to get the post processes on.
  67024. * @returns The list of the post processes in the effect.
  67025. */
  67026. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  67027. if (this._singleInstance) {
  67028. return this._postProcesses[0];
  67029. }
  67030. else {
  67031. if (!camera) {
  67032. return null;
  67033. }
  67034. return this._postProcesses[camera.name];
  67035. }
  67036. };
  67037. return PostProcessRenderEffect;
  67038. }());
  67039. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  67040. })(BABYLON || (BABYLON = {}));
  67041. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  67042. "use strict";
  67043. var BABYLON;
  67044. (function (BABYLON) {
  67045. var PostProcessRenderPipeline = /** @class */ (function () {
  67046. function PostProcessRenderPipeline(engine, name) {
  67047. this.engine = engine;
  67048. this._name = name;
  67049. this._renderEffects = {};
  67050. this._renderEffectsForIsolatedPass = new Array();
  67051. this._cameras = [];
  67052. }
  67053. PostProcessRenderPipeline.prototype.getClassName = function () {
  67054. return "PostProcessRenderPipeline";
  67055. };
  67056. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  67057. get: function () {
  67058. for (var renderEffectName in this._renderEffects) {
  67059. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67060. if (!this._renderEffects[renderEffectName].isSupported) {
  67061. return false;
  67062. }
  67063. }
  67064. }
  67065. return true;
  67066. },
  67067. enumerable: true,
  67068. configurable: true
  67069. });
  67070. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  67071. this._renderEffects[renderEffect._name] = renderEffect;
  67072. };
  67073. // private
  67074. PostProcessRenderPipeline.prototype._rebuild = function () {
  67075. };
  67076. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  67077. var renderEffects = this._renderEffects[renderEffectName];
  67078. if (!renderEffects) {
  67079. return;
  67080. }
  67081. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  67082. };
  67083. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  67084. var renderEffects = this._renderEffects[renderEffectName];
  67085. if (!renderEffects) {
  67086. return;
  67087. }
  67088. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  67089. };
  67090. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  67091. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67092. if (!cams) {
  67093. return;
  67094. }
  67095. var indicesToDelete = [];
  67096. var i;
  67097. for (i = 0; i < cams.length; i++) {
  67098. var camera = cams[i];
  67099. var cameraName = camera.name;
  67100. if (this._cameras.indexOf(camera) === -1) {
  67101. this._cameras[cameraName] = camera;
  67102. }
  67103. else if (unique) {
  67104. indicesToDelete.push(i);
  67105. }
  67106. }
  67107. for (i = 0; i < indicesToDelete.length; i++) {
  67108. cameras.splice(indicesToDelete[i], 1);
  67109. }
  67110. for (var renderEffectName in this._renderEffects) {
  67111. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67112. this._renderEffects[renderEffectName]._attachCameras(cams);
  67113. }
  67114. }
  67115. };
  67116. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  67117. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67118. if (!cams) {
  67119. return;
  67120. }
  67121. for (var renderEffectName in this._renderEffects) {
  67122. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67123. this._renderEffects[renderEffectName]._detachCameras(cams);
  67124. }
  67125. }
  67126. for (var i = 0; i < cams.length; i++) {
  67127. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  67128. }
  67129. };
  67130. PostProcessRenderPipeline.prototype._update = function () {
  67131. for (var renderEffectName in this._renderEffects) {
  67132. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67133. this._renderEffects[renderEffectName]._update();
  67134. }
  67135. }
  67136. for (var i = 0; i < this._cameras.length; i++) {
  67137. var cameraName = this._cameras[i].name;
  67138. if (this._renderEffectsForIsolatedPass[cameraName]) {
  67139. this._renderEffectsForIsolatedPass[cameraName]._update();
  67140. }
  67141. }
  67142. };
  67143. PostProcessRenderPipeline.prototype._reset = function () {
  67144. this._renderEffects = {};
  67145. this._renderEffectsForIsolatedPass = new Array();
  67146. };
  67147. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function () {
  67148. // Set samples of the very first post process to 4 to enable native anti-aliasing in browsers that support webGL 2.0 (See: https://github.com/BabylonJS/Babylon.js/issues/3754)
  67149. var effectKeys = Object.keys(this._renderEffects);
  67150. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  67151. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  67152. if (postProcesses) {
  67153. postProcesses[0].samples = 4;
  67154. return true;
  67155. }
  67156. }
  67157. return false;
  67158. };
  67159. PostProcessRenderPipeline.prototype.dispose = function () {
  67160. // Must be implemented by children
  67161. };
  67162. __decorate([
  67163. BABYLON.serialize()
  67164. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  67165. return PostProcessRenderPipeline;
  67166. }());
  67167. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  67168. })(BABYLON || (BABYLON = {}));
  67169. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  67170. "use strict";
  67171. var BABYLON;
  67172. (function (BABYLON) {
  67173. /**
  67174. * This represents a depth renderer in Babylon.
  67175. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  67176. */
  67177. var DepthRenderer = /** @class */ (function () {
  67178. /**
  67179. * Instantiates a depth renderer
  67180. * @param scene The scene the renderer belongs to
  67181. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  67182. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  67183. */
  67184. function DepthRenderer(scene, type, camera) {
  67185. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  67186. if (camera === void 0) { camera = null; }
  67187. var _this = this;
  67188. this._scene = scene;
  67189. this._camera = camera;
  67190. var engine = scene.getEngine();
  67191. // Render target
  67192. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  67193. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67194. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67195. this._depthMap.refreshRate = 1;
  67196. this._depthMap.renderParticles = false;
  67197. this._depthMap.renderList = null;
  67198. // Camera to get depth map from to support multiple concurrent cameras
  67199. this._depthMap.activeCamera = this._camera;
  67200. this._depthMap.ignoreCameraViewport = true;
  67201. this._depthMap.useCameraPostProcesses = false;
  67202. // set default depth value to 1.0 (far away)
  67203. this._depthMap.onClearObservable.add(function (engine) {
  67204. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  67205. });
  67206. // Custom render function
  67207. var renderSubMesh = function (subMesh) {
  67208. var mesh = subMesh.getRenderingMesh();
  67209. var scene = _this._scene;
  67210. var engine = scene.getEngine();
  67211. var material = subMesh.getMaterial();
  67212. if (!material) {
  67213. return;
  67214. }
  67215. // Culling and reverse (right handed system)
  67216. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  67217. // Managing instances
  67218. var batch = mesh._getInstancesRenderList(subMesh._id);
  67219. if (batch.mustReturn) {
  67220. return;
  67221. }
  67222. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  67223. var camera = _this._camera || scene.activeCamera;
  67224. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  67225. engine.enableEffect(_this._effect);
  67226. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  67227. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  67228. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  67229. // Alpha test
  67230. if (material && material.needAlphaTesting()) {
  67231. var alphaTexture = material.getAlphaTestTexture();
  67232. if (alphaTexture) {
  67233. _this._effect.setTexture("diffuseSampler", alphaTexture);
  67234. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67235. }
  67236. }
  67237. // Bones
  67238. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67239. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67240. }
  67241. // Draw
  67242. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  67243. }
  67244. };
  67245. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67246. var index;
  67247. if (depthOnlySubMeshes.length) {
  67248. engine.setColorWrite(false);
  67249. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67250. renderSubMesh(depthOnlySubMeshes.data[index]);
  67251. }
  67252. engine.setColorWrite(true);
  67253. }
  67254. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67255. renderSubMesh(opaqueSubMeshes.data[index]);
  67256. }
  67257. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67258. renderSubMesh(alphaTestSubMeshes.data[index]);
  67259. }
  67260. };
  67261. }
  67262. /**
  67263. * Creates the depth rendering effect and checks if the effect is ready.
  67264. * @param subMesh The submesh to be used to render the depth map of
  67265. * @param useInstances If multiple world instances should be used
  67266. * @returns if the depth renderer is ready to render the depth map
  67267. */
  67268. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  67269. var material = subMesh.getMaterial();
  67270. if (material.disableDepthWrite) {
  67271. return false;
  67272. }
  67273. var defines = [];
  67274. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67275. var mesh = subMesh.getMesh();
  67276. // Alpha test
  67277. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  67278. defines.push("#define ALPHATEST");
  67279. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67280. attribs.push(BABYLON.VertexBuffer.UVKind);
  67281. defines.push("#define UV1");
  67282. }
  67283. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67284. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67285. defines.push("#define UV2");
  67286. }
  67287. }
  67288. // Bones
  67289. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67290. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67291. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67292. if (mesh.numBoneInfluencers > 4) {
  67293. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67294. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67295. }
  67296. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67297. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  67298. }
  67299. else {
  67300. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67301. }
  67302. // Instances
  67303. if (useInstances) {
  67304. defines.push("#define INSTANCES");
  67305. attribs.push("world0");
  67306. attribs.push("world1");
  67307. attribs.push("world2");
  67308. attribs.push("world3");
  67309. }
  67310. // Get correct effect
  67311. var join = defines.join("\n");
  67312. if (this._cachedDefines !== join) {
  67313. this._cachedDefines = join;
  67314. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  67315. }
  67316. return this._effect.isReady();
  67317. };
  67318. /**
  67319. * Gets the texture which the depth map will be written to.
  67320. * @returns The depth map texture
  67321. */
  67322. DepthRenderer.prototype.getDepthMap = function () {
  67323. return this._depthMap;
  67324. };
  67325. /**
  67326. * Disposes of the depth renderer.
  67327. */
  67328. DepthRenderer.prototype.dispose = function () {
  67329. this._depthMap.dispose();
  67330. };
  67331. return DepthRenderer;
  67332. }());
  67333. BABYLON.DepthRenderer = DepthRenderer;
  67334. })(BABYLON || (BABYLON = {}));
  67335. //# sourceMappingURL=babylon.depthRenderer.js.map
  67336. "use strict";
  67337. var BABYLON;
  67338. (function (BABYLON) {
  67339. var SSAORenderingPipeline = /** @class */ (function (_super) {
  67340. __extends(SSAORenderingPipeline, _super);
  67341. /**
  67342. * @constructor
  67343. * @param {string} name - The rendering pipeline name
  67344. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67345. * @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 }
  67346. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67347. */
  67348. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  67349. var _this = _super.call(this, scene.getEngine(), name) || this;
  67350. // Members
  67351. /**
  67352. * The PassPostProcess id in the pipeline that contains the original scene color
  67353. * @type {string}
  67354. */
  67355. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  67356. /**
  67357. * The SSAO PostProcess id in the pipeline
  67358. * @type {string}
  67359. */
  67360. _this.SSAORenderEffect = "SSAORenderEffect";
  67361. /**
  67362. * The horizontal blur PostProcess id in the pipeline
  67363. * @type {string}
  67364. */
  67365. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  67366. /**
  67367. * The vertical blur PostProcess id in the pipeline
  67368. * @type {string}
  67369. */
  67370. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  67371. /**
  67372. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  67373. * @type {string}
  67374. */
  67375. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  67376. /**
  67377. * The output strength of the SSAO post-process. Default value is 1.0.
  67378. * @type {number}
  67379. */
  67380. _this.totalStrength = 1.0;
  67381. /**
  67382. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  67383. * @type {number}
  67384. */
  67385. _this.radius = 0.0001;
  67386. /**
  67387. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  67388. * Must not be equal to fallOff and superior to fallOff.
  67389. * Default value is 0.975
  67390. * @type {number}
  67391. */
  67392. _this.area = 0.0075;
  67393. /**
  67394. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  67395. * Must not be equal to area and inferior to area.
  67396. * Default value is 0.0
  67397. * @type {number}
  67398. */
  67399. _this.fallOff = 0.000001;
  67400. /**
  67401. * The base color of the SSAO post-process
  67402. * The final result is "base + ssao" between [0, 1]
  67403. * @type {number}
  67404. */
  67405. _this.base = 0.5;
  67406. _this._firstUpdate = true;
  67407. _this._scene = scene;
  67408. // Set up assets
  67409. _this._createRandomTexture();
  67410. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  67411. var ssaoRatio = ratio.ssaoRatio || ratio;
  67412. var combineRatio = ratio.combineRatio || ratio;
  67413. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  67414. _this._createSSAOPostProcess(ssaoRatio);
  67415. _this._createBlurPostProcess(ssaoRatio);
  67416. _this._createSSAOCombinePostProcess(combineRatio);
  67417. // Set up pipeline
  67418. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  67419. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  67420. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  67421. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  67422. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  67423. // Finish
  67424. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67425. if (cameras)
  67426. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67427. return _this;
  67428. }
  67429. // Public Methods
  67430. /**
  67431. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  67432. */
  67433. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  67434. if (disableDepthRender === void 0) { disableDepthRender = false; }
  67435. for (var i = 0; i < this._scene.cameras.length; i++) {
  67436. var camera = this._scene.cameras[i];
  67437. this._originalColorPostProcess.dispose(camera);
  67438. this._ssaoPostProcess.dispose(camera);
  67439. this._blurHPostProcess.dispose(camera);
  67440. this._blurVPostProcess.dispose(camera);
  67441. this._ssaoCombinePostProcess.dispose(camera);
  67442. }
  67443. this._randomTexture.dispose();
  67444. if (disableDepthRender)
  67445. this._scene.disableDepthRenderer();
  67446. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67447. _super.prototype.dispose.call(this);
  67448. };
  67449. // Private Methods
  67450. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  67451. var _this = this;
  67452. var size = 16;
  67453. 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);
  67454. 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);
  67455. this._blurHPostProcess.onActivateObservable.add(function () {
  67456. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  67457. _this._blurHPostProcess.kernel = size * dw;
  67458. });
  67459. this._blurVPostProcess.onActivateObservable.add(function () {
  67460. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  67461. _this._blurVPostProcess.kernel = size * dw;
  67462. });
  67463. };
  67464. SSAORenderingPipeline.prototype._rebuild = function () {
  67465. this._firstUpdate = true;
  67466. _super.prototype._rebuild.call(this);
  67467. };
  67468. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  67469. var _this = this;
  67470. var numSamples = 16;
  67471. var sampleSphere = [
  67472. 0.5381, 0.1856, -0.4319,
  67473. 0.1379, 0.2486, 0.4430,
  67474. 0.3371, 0.5679, -0.0057,
  67475. -0.6999, -0.0451, -0.0019,
  67476. 0.0689, -0.1598, -0.8547,
  67477. 0.0560, 0.0069, -0.1843,
  67478. -0.0146, 0.1402, 0.0762,
  67479. 0.0100, -0.1924, -0.0344,
  67480. -0.3577, -0.5301, -0.4358,
  67481. -0.3169, 0.1063, 0.0158,
  67482. 0.0103, -0.5869, 0.0046,
  67483. -0.0897, -0.4940, 0.3287,
  67484. 0.7119, -0.0154, -0.0918,
  67485. -0.0533, 0.0596, -0.5411,
  67486. 0.0352, -0.0631, 0.5460,
  67487. -0.4776, 0.2847, -0.0271
  67488. ];
  67489. var samplesFactor = 1.0 / numSamples;
  67490. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  67491. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  67492. "area", "fallOff", "base", "range", "viewport"
  67493. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  67494. this._ssaoPostProcess.onApply = function (effect) {
  67495. if (_this._firstUpdate) {
  67496. effect.setArray3("sampleSphere", sampleSphere);
  67497. effect.setFloat("samplesFactor", samplesFactor);
  67498. effect.setFloat("randTextureTiles", 4.0);
  67499. }
  67500. effect.setFloat("totalStrength", _this.totalStrength);
  67501. effect.setFloat("radius", _this.radius);
  67502. effect.setFloat("area", _this.area);
  67503. effect.setFloat("fallOff", _this.fallOff);
  67504. effect.setFloat("base", _this.base);
  67505. effect.setTexture("textureSampler", _this._depthTexture);
  67506. effect.setTexture("randomSampler", _this._randomTexture);
  67507. };
  67508. };
  67509. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  67510. var _this = this;
  67511. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67512. this._ssaoCombinePostProcess.onApply = function (effect) {
  67513. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  67514. };
  67515. };
  67516. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  67517. var size = 512;
  67518. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67519. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67520. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67521. var context = this._randomTexture.getContext();
  67522. var rand = function (min, max) {
  67523. return Math.random() * (max - min) + min;
  67524. };
  67525. var randVector = BABYLON.Vector3.Zero();
  67526. for (var x = 0; x < size; x++) {
  67527. for (var y = 0; y < size; y++) {
  67528. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  67529. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  67530. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  67531. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  67532. context.fillRect(x, y, 1, 1);
  67533. }
  67534. }
  67535. this._randomTexture.update(false);
  67536. };
  67537. __decorate([
  67538. BABYLON.serialize()
  67539. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  67540. __decorate([
  67541. BABYLON.serialize()
  67542. ], SSAORenderingPipeline.prototype, "radius", void 0);
  67543. __decorate([
  67544. BABYLON.serialize()
  67545. ], SSAORenderingPipeline.prototype, "area", void 0);
  67546. __decorate([
  67547. BABYLON.serialize()
  67548. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  67549. __decorate([
  67550. BABYLON.serialize()
  67551. ], SSAORenderingPipeline.prototype, "base", void 0);
  67552. return SSAORenderingPipeline;
  67553. }(BABYLON.PostProcessRenderPipeline));
  67554. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  67555. })(BABYLON || (BABYLON = {}));
  67556. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  67557. "use strict";
  67558. var BABYLON;
  67559. (function (BABYLON) {
  67560. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  67561. __extends(SSAO2RenderingPipeline, _super);
  67562. /**
  67563. * @constructor
  67564. * @param {string} name - The rendering pipeline name
  67565. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67566. * @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 }
  67567. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67568. */
  67569. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  67570. var _this = _super.call(this, scene.getEngine(), name) || this;
  67571. // Members
  67572. /**
  67573. * The PassPostProcess id in the pipeline that contains the original scene color
  67574. * @type {string}
  67575. */
  67576. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  67577. /**
  67578. * The SSAO PostProcess id in the pipeline
  67579. * @type {string}
  67580. */
  67581. _this.SSAORenderEffect = "SSAORenderEffect";
  67582. /**
  67583. * The horizontal blur PostProcess id in the pipeline
  67584. * @type {string}
  67585. */
  67586. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  67587. /**
  67588. * The vertical blur PostProcess id in the pipeline
  67589. * @type {string}
  67590. */
  67591. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  67592. /**
  67593. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  67594. * @type {string}
  67595. */
  67596. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  67597. /**
  67598. * The output strength of the SSAO post-process. Default value is 1.0.
  67599. * @type {number}
  67600. */
  67601. _this.totalStrength = 1.0;
  67602. /**
  67603. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  67604. * @type {number}
  67605. */
  67606. _this.maxZ = 100.0;
  67607. /**
  67608. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  67609. * @type {number}
  67610. */
  67611. _this.minZAspect = 0.2;
  67612. /**
  67613. * Number of samples used for the SSAO calculations. Default value is 8
  67614. * @type {number}
  67615. */
  67616. _this._samples = 8;
  67617. /**
  67618. * Are we using bilateral blur ?
  67619. * @type {boolean}
  67620. */
  67621. _this._expensiveBlur = true;
  67622. /**
  67623. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  67624. * @type {number}
  67625. */
  67626. _this.radius = 2.0;
  67627. /**
  67628. * The base color of the SSAO post-process
  67629. * The final result is "base + ssao" between [0, 1]
  67630. * @type {number}
  67631. */
  67632. _this.base = 0.1;
  67633. _this._firstUpdate = true;
  67634. _this._scene = scene;
  67635. if (!_this.isSupported) {
  67636. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  67637. return _this;
  67638. }
  67639. var ssaoRatio = ratio.ssaoRatio || ratio;
  67640. var blurRatio = ratio.blurRatio || ratio;
  67641. // Set up assets
  67642. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  67643. _this._createRandomTexture();
  67644. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  67645. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  67646. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  67647. _this._createSSAOPostProcess(1.0);
  67648. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  67649. _this._createSSAOCombinePostProcess(blurRatio);
  67650. // Set up pipeline
  67651. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  67652. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  67653. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  67654. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  67655. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  67656. // Finish
  67657. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67658. if (cameras)
  67659. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67660. return _this;
  67661. }
  67662. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  67663. get: function () {
  67664. return this._samples;
  67665. },
  67666. set: function (n) {
  67667. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  67668. this._samples = n;
  67669. this._sampleSphere = this._generateHemisphere();
  67670. this._firstUpdate = true;
  67671. },
  67672. enumerable: true,
  67673. configurable: true
  67674. });
  67675. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  67676. get: function () {
  67677. return this._expensiveBlur;
  67678. },
  67679. set: function (b) {
  67680. 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"]);
  67681. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  67682. this._expensiveBlur = b;
  67683. this._firstUpdate = true;
  67684. },
  67685. enumerable: true,
  67686. configurable: true
  67687. });
  67688. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  67689. /**
  67690. * Support test.
  67691. * @type {boolean}
  67692. */
  67693. get: function () {
  67694. var engine = BABYLON.Engine.LastCreatedEngine;
  67695. if (!engine) {
  67696. return false;
  67697. }
  67698. return engine.getCaps().drawBuffersExtension;
  67699. },
  67700. enumerable: true,
  67701. configurable: true
  67702. });
  67703. // Public Methods
  67704. /**
  67705. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  67706. */
  67707. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  67708. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  67709. for (var i = 0; i < this._scene.cameras.length; i++) {
  67710. var camera = this._scene.cameras[i];
  67711. this._originalColorPostProcess.dispose(camera);
  67712. this._ssaoPostProcess.dispose(camera);
  67713. this._blurHPostProcess.dispose(camera);
  67714. this._blurVPostProcess.dispose(camera);
  67715. this._ssaoCombinePostProcess.dispose(camera);
  67716. }
  67717. this._randomTexture.dispose();
  67718. if (disableGeometryBufferRenderer)
  67719. this._scene.disableGeometryBufferRenderer();
  67720. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67721. _super.prototype.dispose.call(this);
  67722. };
  67723. // Private Methods
  67724. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  67725. var _this = this;
  67726. this._samplerOffsets = [];
  67727. var expensive = this.expensiveBlur;
  67728. for (var i = -8; i < 8; i++) {
  67729. this._samplerOffsets.push(i * 2 + 0.5);
  67730. }
  67731. 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");
  67732. this._blurHPostProcess.onApply = function (effect) {
  67733. if (!_this._scene.activeCamera) {
  67734. return;
  67735. }
  67736. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  67737. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67738. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67739. effect.setFloat("radius", _this.radius);
  67740. effect.setTexture("depthSampler", _this._depthTexture);
  67741. if (_this._firstUpdate) {
  67742. effect.setArray("samplerOffsets", _this._samplerOffsets);
  67743. }
  67744. };
  67745. 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");
  67746. this._blurVPostProcess.onApply = function (effect) {
  67747. if (!_this._scene.activeCamera) {
  67748. return;
  67749. }
  67750. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  67751. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67752. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67753. effect.setFloat("radius", _this.radius);
  67754. effect.setTexture("depthSampler", _this._depthTexture);
  67755. if (_this._firstUpdate) {
  67756. effect.setArray("samplerOffsets", _this._samplerOffsets);
  67757. _this._firstUpdate = false;
  67758. }
  67759. };
  67760. };
  67761. SSAO2RenderingPipeline.prototype._rebuild = function () {
  67762. this._firstUpdate = true;
  67763. _super.prototype._rebuild.call(this);
  67764. };
  67765. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  67766. var numSamples = this.samples;
  67767. var result = [];
  67768. var vector, scale;
  67769. var rand = function (min, max) {
  67770. return Math.random() * (max - min) + min;
  67771. };
  67772. var i = 0;
  67773. while (i < numSamples) {
  67774. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  67775. vector.normalize();
  67776. scale = i / numSamples;
  67777. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  67778. vector.scaleInPlace(scale);
  67779. result.push(vector.x, vector.y, vector.z);
  67780. i++;
  67781. }
  67782. return result;
  67783. };
  67784. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  67785. var _this = this;
  67786. var numSamples = this.samples;
  67787. this._sampleSphere = this._generateHemisphere();
  67788. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  67789. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  67790. "base", "range", "projection", "near", "far", "texelSize",
  67791. "xViewport", "yViewport", "maxZ", "minZAspect"
  67792. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  67793. this._ssaoPostProcess.onApply = function (effect) {
  67794. if (_this._firstUpdate) {
  67795. effect.setArray3("sampleSphere", _this._sampleSphere);
  67796. effect.setFloat("randTextureTiles", 4.0);
  67797. }
  67798. if (!_this._scene.activeCamera) {
  67799. return;
  67800. }
  67801. effect.setFloat("samplesFactor", 1 / _this.samples);
  67802. effect.setFloat("totalStrength", _this.totalStrength);
  67803. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  67804. effect.setFloat("radius", _this.radius);
  67805. effect.setFloat("maxZ", _this.maxZ);
  67806. effect.setFloat("minZAspect", _this.minZAspect);
  67807. effect.setFloat("base", _this.base);
  67808. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67809. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67810. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  67811. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  67812. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  67813. effect.setTexture("textureSampler", _this._depthTexture);
  67814. effect.setTexture("normalSampler", _this._normalTexture);
  67815. effect.setTexture("randomSampler", _this._randomTexture);
  67816. };
  67817. };
  67818. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  67819. var _this = this;
  67820. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67821. this._ssaoCombinePostProcess.onApply = function (effect) {
  67822. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  67823. };
  67824. };
  67825. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  67826. var size = 512;
  67827. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67828. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67829. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67830. var context = this._randomTexture.getContext();
  67831. var rand = function (min, max) {
  67832. return Math.random() * (max - min) + min;
  67833. };
  67834. var randVector = BABYLON.Vector3.Zero();
  67835. for (var x = 0; x < size; x++) {
  67836. for (var y = 0; y < size; y++) {
  67837. randVector.x = rand(0.0, 1.0);
  67838. randVector.y = rand(0.0, 1.0);
  67839. randVector.z = 0.0;
  67840. randVector.normalize();
  67841. randVector.scaleInPlace(255);
  67842. randVector.x = Math.floor(randVector.x);
  67843. randVector.y = Math.floor(randVector.y);
  67844. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  67845. context.fillRect(x, y, 1, 1);
  67846. }
  67847. }
  67848. this._randomTexture.update(false);
  67849. };
  67850. __decorate([
  67851. BABYLON.serialize()
  67852. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  67853. __decorate([
  67854. BABYLON.serialize()
  67855. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  67856. __decorate([
  67857. BABYLON.serialize()
  67858. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  67859. __decorate([
  67860. BABYLON.serialize("samples")
  67861. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  67862. __decorate([
  67863. BABYLON.serialize("expensiveBlur")
  67864. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  67865. __decorate([
  67866. BABYLON.serialize()
  67867. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  67868. __decorate([
  67869. BABYLON.serialize()
  67870. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  67871. return SSAO2RenderingPipeline;
  67872. }(BABYLON.PostProcessRenderPipeline));
  67873. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  67874. })(BABYLON || (BABYLON = {}));
  67875. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  67876. "use strict";
  67877. // BABYLON.JS Chromatic Aberration GLSL Shader
  67878. // Author: Olivier Guyot
  67879. // Separates very slightly R, G and B colors on the edges of the screen
  67880. // Inspired by Francois Tarlier & Martins Upitis
  67881. var BABYLON;
  67882. (function (BABYLON) {
  67883. var LensRenderingPipeline = /** @class */ (function (_super) {
  67884. __extends(LensRenderingPipeline, _super);
  67885. /**
  67886. * @constructor
  67887. *
  67888. * Effect parameters are as follow:
  67889. * {
  67890. * chromatic_aberration: number; // from 0 to x (1 for realism)
  67891. * edge_blur: number; // from 0 to x (1 for realism)
  67892. * distortion: number; // from 0 to x (1 for realism)
  67893. * grain_amount: number; // from 0 to 1
  67894. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  67895. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  67896. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  67897. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  67898. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  67899. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  67900. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  67901. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  67902. * }
  67903. * Note: if an effect parameter is unset, effect is disabled
  67904. *
  67905. * @param {string} name - The rendering pipeline name
  67906. * @param {object} parameters - An object containing all parameters (see above)
  67907. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67908. * @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)
  67909. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67910. */
  67911. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  67912. if (ratio === void 0) { ratio = 1.0; }
  67913. var _this = _super.call(this, scene.getEngine(), name) || this;
  67914. // Lens effects can be of the following:
  67915. // - chromatic aberration (slight shift of RGB colors)
  67916. // - blur on the edge of the lens
  67917. // - lens distortion
  67918. // - depth-of-field blur & highlights enhancing
  67919. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  67920. // - grain effect (noise or custom texture)
  67921. // Two additional texture samplers are needed:
  67922. // - depth map (for depth-of-field)
  67923. // - grain texture
  67924. /**
  67925. * The chromatic aberration PostProcess id in the pipeline
  67926. * @type {string}
  67927. */
  67928. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  67929. /**
  67930. * The highlights enhancing PostProcess id in the pipeline
  67931. * @type {string}
  67932. */
  67933. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  67934. /**
  67935. * The depth-of-field PostProcess id in the pipeline
  67936. * @type {string}
  67937. */
  67938. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  67939. _this._scene = scene;
  67940. // Fetch texture samplers
  67941. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  67942. if (parameters.grain_texture) {
  67943. _this._grainTexture = parameters.grain_texture;
  67944. }
  67945. else {
  67946. _this._createGrainTexture();
  67947. }
  67948. // save parameters
  67949. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  67950. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  67951. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  67952. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  67953. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  67954. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  67955. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  67956. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  67957. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  67958. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  67959. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  67960. // Create effects
  67961. _this._createChromaticAberrationPostProcess(ratio);
  67962. _this._createHighlightsPostProcess(ratio);
  67963. _this._createDepthOfFieldPostProcess(ratio / 4);
  67964. // Set up pipeline
  67965. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  67966. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  67967. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  67968. if (_this._highlightsGain === -1) {
  67969. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  67970. }
  67971. // Finish
  67972. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67973. if (cameras) {
  67974. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67975. }
  67976. return _this;
  67977. }
  67978. // public methods (self explanatory)
  67979. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  67980. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  67981. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  67982. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  67983. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  67984. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  67985. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  67986. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  67987. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  67988. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  67989. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  67990. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  67991. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  67992. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  67993. };
  67994. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  67995. this._highlightsPostProcess.updateEffect();
  67996. };
  67997. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  67998. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  67999. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  68000. this._highlightsGain = amount;
  68001. };
  68002. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  68003. if (this._highlightsGain === -1) {
  68004. this._highlightsGain = 1.0;
  68005. }
  68006. this._highlightsThreshold = amount;
  68007. };
  68008. LensRenderingPipeline.prototype.disableHighlights = function () {
  68009. this._highlightsGain = -1;
  68010. };
  68011. /**
  68012. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  68013. */
  68014. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  68015. if (disableDepthRender === void 0) { disableDepthRender = false; }
  68016. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68017. this._chromaticAberrationPostProcess = null;
  68018. this._highlightsPostProcess = null;
  68019. this._depthOfFieldPostProcess = null;
  68020. this._grainTexture.dispose();
  68021. if (disableDepthRender)
  68022. this._scene.disableDepthRenderer();
  68023. };
  68024. // colors shifting and distortion
  68025. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  68026. var _this = this;
  68027. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  68028. [], // samplers
  68029. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68030. this._chromaticAberrationPostProcess.onApply = function (effect) {
  68031. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  68032. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  68033. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  68034. effect.setFloat('radialIntensity', 1);
  68035. effect.setFloat2('direction', 17, 17);
  68036. effect.setFloat2('centerPosition', 0.5, 0.5);
  68037. };
  68038. };
  68039. // highlights enhancing
  68040. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  68041. var _this = this;
  68042. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  68043. [], // samplers
  68044. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  68045. this._highlightsPostProcess.onApply = function (effect) {
  68046. effect.setFloat('gain', _this._highlightsGain);
  68047. effect.setFloat('threshold', _this._highlightsThreshold);
  68048. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  68049. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  68050. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  68051. };
  68052. };
  68053. // colors shifting and distortion
  68054. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  68055. var _this = this;
  68056. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  68057. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  68058. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  68059. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68060. this._depthOfFieldPostProcess.onApply = function (effect) {
  68061. effect.setTexture("depthSampler", _this._depthTexture);
  68062. effect.setTexture("grainSampler", _this._grainTexture);
  68063. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  68064. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  68065. effect.setFloat('grain_amount', _this._grainAmount);
  68066. effect.setBool('blur_noise', _this._blurNoise);
  68067. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  68068. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  68069. effect.setFloat('distortion', _this._distortion);
  68070. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  68071. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  68072. effect.setFloat('aperture', _this._dofAperture);
  68073. effect.setFloat('darken', _this._dofDarken);
  68074. effect.setFloat('edge_blur', _this._edgeBlur);
  68075. effect.setBool('highlights', (_this._highlightsGain !== -1));
  68076. if (_this._scene.activeCamera) {
  68077. effect.setFloat('near', _this._scene.activeCamera.minZ);
  68078. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  68079. }
  68080. };
  68081. };
  68082. // creates a black and white random noise texture, 512x512
  68083. LensRenderingPipeline.prototype._createGrainTexture = function () {
  68084. var size = 512;
  68085. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68086. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68087. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68088. var context = this._grainTexture.getContext();
  68089. var rand = function (min, max) {
  68090. return Math.random() * (max - min) + min;
  68091. };
  68092. var value;
  68093. for (var x = 0; x < size; x++) {
  68094. for (var y = 0; y < size; y++) {
  68095. value = Math.floor(rand(0.42, 0.58) * 255);
  68096. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  68097. context.fillRect(x, y, 1, 1);
  68098. }
  68099. }
  68100. this._grainTexture.update(false);
  68101. };
  68102. return LensRenderingPipeline;
  68103. }(BABYLON.PostProcessRenderPipeline));
  68104. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  68105. })(BABYLON || (BABYLON = {}));
  68106. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  68107. "use strict";
  68108. var BABYLON;
  68109. (function (BABYLON) {
  68110. var StandardRenderingPipeline = /** @class */ (function (_super) {
  68111. __extends(StandardRenderingPipeline, _super);
  68112. /**
  68113. * @constructor
  68114. * @param {string} name - The rendering pipeline name
  68115. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68116. * @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)
  68117. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  68118. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68119. */
  68120. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  68121. if (originalPostProcess === void 0) { originalPostProcess = null; }
  68122. var _this = _super.call(this, scene.getEngine(), name) || this;
  68123. _this.downSampleX4PostProcess = null;
  68124. _this.brightPassPostProcess = null;
  68125. _this.blurHPostProcesses = [];
  68126. _this.blurVPostProcesses = [];
  68127. _this.textureAdderPostProcess = null;
  68128. _this.volumetricLightPostProcess = null;
  68129. _this.volumetricLightSmoothXPostProcess = null;
  68130. _this.volumetricLightSmoothYPostProcess = null;
  68131. _this.volumetricLightMergePostProces = null;
  68132. _this.volumetricLightFinalPostProcess = null;
  68133. _this.luminancePostProcess = null;
  68134. _this.luminanceDownSamplePostProcesses = [];
  68135. _this.hdrPostProcess = null;
  68136. _this.textureAdderFinalPostProcess = null;
  68137. _this.lensFlareFinalPostProcess = null;
  68138. _this.hdrFinalPostProcess = null;
  68139. _this.lensFlarePostProcess = null;
  68140. _this.lensFlareComposePostProcess = null;
  68141. _this.motionBlurPostProcess = null;
  68142. _this.depthOfFieldPostProcess = null;
  68143. // Values
  68144. _this.brightThreshold = 1.0;
  68145. _this.blurWidth = 512.0;
  68146. _this.horizontalBlur = false;
  68147. _this.exposure = 1.0;
  68148. _this.lensTexture = null;
  68149. _this.volumetricLightCoefficient = 0.2;
  68150. _this.volumetricLightPower = 4.0;
  68151. _this.volumetricLightBlurScale = 64.0;
  68152. _this.sourceLight = null;
  68153. _this.hdrMinimumLuminance = 1.0;
  68154. _this.hdrDecreaseRate = 0.5;
  68155. _this.hdrIncreaseRate = 0.5;
  68156. _this.lensColorTexture = null;
  68157. _this.lensFlareStrength = 20.0;
  68158. _this.lensFlareGhostDispersal = 1.4;
  68159. _this.lensFlareHaloWidth = 0.7;
  68160. _this.lensFlareDistortionStrength = 16.0;
  68161. _this.lensStarTexture = null;
  68162. _this.lensFlareDirtTexture = null;
  68163. _this.depthOfFieldDistance = 10.0;
  68164. _this.depthOfFieldBlurWidth = 64.0;
  68165. _this.motionStrength = 1.0;
  68166. // IAnimatable
  68167. _this.animations = [];
  68168. _this._currentDepthOfFieldSource = null;
  68169. _this._hdrCurrentLuminance = 1.0;
  68170. // Getters and setters
  68171. _this._bloomEnabled = true;
  68172. _this._depthOfFieldEnabled = false;
  68173. _this._vlsEnabled = false;
  68174. _this._lensFlareEnabled = false;
  68175. _this._hdrEnabled = false;
  68176. _this._motionBlurEnabled = false;
  68177. _this._motionBlurSamples = 64.0;
  68178. _this._volumetricLightStepsCount = 50.0;
  68179. _this._cameras = cameras || [];
  68180. // Initialize
  68181. _this._scene = scene;
  68182. _this._basePostProcess = originalPostProcess;
  68183. _this._ratio = ratio;
  68184. // Misc
  68185. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68186. // Finish
  68187. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68188. _this._buildPipeline();
  68189. return _this;
  68190. }
  68191. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  68192. get: function () {
  68193. return this._bloomEnabled;
  68194. },
  68195. set: function (enabled) {
  68196. if (this._bloomEnabled === enabled) {
  68197. return;
  68198. }
  68199. this._bloomEnabled = enabled;
  68200. this._buildPipeline();
  68201. },
  68202. enumerable: true,
  68203. configurable: true
  68204. });
  68205. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  68206. get: function () {
  68207. return this._depthOfFieldEnabled;
  68208. },
  68209. set: function (enabled) {
  68210. if (this._depthOfFieldEnabled === enabled) {
  68211. return;
  68212. }
  68213. this._depthOfFieldEnabled = enabled;
  68214. this._buildPipeline();
  68215. },
  68216. enumerable: true,
  68217. configurable: true
  68218. });
  68219. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  68220. get: function () {
  68221. return this._lensFlareEnabled;
  68222. },
  68223. set: function (enabled) {
  68224. if (this._lensFlareEnabled === enabled) {
  68225. return;
  68226. }
  68227. this._lensFlareEnabled = enabled;
  68228. this._buildPipeline();
  68229. },
  68230. enumerable: true,
  68231. configurable: true
  68232. });
  68233. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  68234. get: function () {
  68235. return this._hdrEnabled;
  68236. },
  68237. set: function (enabled) {
  68238. if (this._hdrEnabled === enabled) {
  68239. return;
  68240. }
  68241. this._hdrEnabled = enabled;
  68242. this._buildPipeline();
  68243. },
  68244. enumerable: true,
  68245. configurable: true
  68246. });
  68247. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  68248. get: function () {
  68249. return this._vlsEnabled;
  68250. },
  68251. set: function (enabled) {
  68252. if (this._vlsEnabled === enabled) {
  68253. return;
  68254. }
  68255. if (enabled) {
  68256. var geometry = this._scene.enableGeometryBufferRenderer();
  68257. if (!geometry) {
  68258. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  68259. return;
  68260. }
  68261. }
  68262. this._vlsEnabled = enabled;
  68263. this._buildPipeline();
  68264. },
  68265. enumerable: true,
  68266. configurable: true
  68267. });
  68268. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  68269. get: function () {
  68270. return this._motionBlurEnabled;
  68271. },
  68272. set: function (enabled) {
  68273. if (this._motionBlurEnabled === enabled) {
  68274. return;
  68275. }
  68276. this._motionBlurEnabled = enabled;
  68277. this._buildPipeline();
  68278. },
  68279. enumerable: true,
  68280. configurable: true
  68281. });
  68282. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  68283. get: function () {
  68284. return this._volumetricLightStepsCount;
  68285. },
  68286. set: function (count) {
  68287. if (this.volumetricLightPostProcess) {
  68288. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  68289. }
  68290. this._volumetricLightStepsCount = count;
  68291. },
  68292. enumerable: true,
  68293. configurable: true
  68294. });
  68295. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  68296. get: function () {
  68297. return this._motionBlurSamples;
  68298. },
  68299. set: function (samples) {
  68300. if (this.motionBlurPostProcess) {
  68301. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  68302. }
  68303. this._motionBlurSamples = samples;
  68304. },
  68305. enumerable: true,
  68306. configurable: true
  68307. });
  68308. StandardRenderingPipeline.prototype._buildPipeline = function () {
  68309. var _this = this;
  68310. var ratio = this._ratio;
  68311. var scene = this._scene;
  68312. this._disposePostProcesses();
  68313. this._reset();
  68314. // Create pass post-process
  68315. if (!this._basePostProcess) {
  68316. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  68317. this.originalPostProcess.onApply = function (effect) {
  68318. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  68319. };
  68320. }
  68321. else {
  68322. this.originalPostProcess = this._basePostProcess;
  68323. }
  68324. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  68325. this._currentDepthOfFieldSource = this.originalPostProcess;
  68326. if (this._vlsEnabled) {
  68327. // Create volumetric light
  68328. this._createVolumetricLightPostProcess(scene, ratio);
  68329. // Create volumetric light final post-process
  68330. 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);
  68331. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  68332. }
  68333. if (this._bloomEnabled) {
  68334. // Create down sample X4 post-process
  68335. this._createDownSampleX4PostProcess(scene, ratio / 2);
  68336. // Create bright pass post-process
  68337. this._createBrightPassPostProcess(scene, ratio / 2);
  68338. // Create gaussian blur post-processes (down sampling blurs)
  68339. this._createBlurPostProcesses(scene, ratio / 4, 1);
  68340. // Create texture adder post-process
  68341. this._createTextureAdderPostProcess(scene, ratio);
  68342. // Create depth-of-field source post-process
  68343. 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);
  68344. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  68345. }
  68346. if (this._lensFlareEnabled) {
  68347. // Create lens flare post-process
  68348. this._createLensFlarePostProcess(scene, ratio);
  68349. // Create depth-of-field source post-process post lens-flare and disable it now
  68350. 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);
  68351. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  68352. }
  68353. if (this._hdrEnabled) {
  68354. // Create luminance
  68355. this._createLuminancePostProcesses(scene, this._floatTextureType);
  68356. // Create HDR
  68357. this._createHdrPostProcess(scene, ratio);
  68358. // Create depth-of-field source post-process post hdr and disable it now
  68359. 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);
  68360. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  68361. }
  68362. if (this._depthOfFieldEnabled) {
  68363. // Create gaussian blur used by depth-of-field
  68364. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  68365. // Create depth-of-field post-process
  68366. this._createDepthOfFieldPostProcess(scene, ratio);
  68367. }
  68368. if (this._motionBlurEnabled) {
  68369. // Create motion blur post-process
  68370. this._createMotionBlurPostProcess(scene, ratio);
  68371. }
  68372. if (this._cameras !== null) {
  68373. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  68374. }
  68375. };
  68376. // Down Sample X4 Post-Processs
  68377. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  68378. var _this = this;
  68379. var downSampleX4Offsets = new Array(32);
  68380. 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);
  68381. this.downSampleX4PostProcess.onApply = function (effect) {
  68382. var id = 0;
  68383. var width = _this.downSampleX4PostProcess.width;
  68384. var height = _this.downSampleX4PostProcess.height;
  68385. for (var i = -2; i < 2; i++) {
  68386. for (var j = -2; j < 2; j++) {
  68387. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  68388. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  68389. id += 2;
  68390. }
  68391. }
  68392. effect.setArray2("dsOffsets", downSampleX4Offsets);
  68393. };
  68394. // Add to pipeline
  68395. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  68396. };
  68397. // Brightpass Post-Process
  68398. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  68399. var _this = this;
  68400. var brightOffsets = new Array(8);
  68401. 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);
  68402. this.brightPassPostProcess.onApply = function (effect) {
  68403. var sU = (1.0 / _this.brightPassPostProcess.width);
  68404. var sV = (1.0 / _this.brightPassPostProcess.height);
  68405. brightOffsets[0] = -0.5 * sU;
  68406. brightOffsets[1] = 0.5 * sV;
  68407. brightOffsets[2] = 0.5 * sU;
  68408. brightOffsets[3] = 0.5 * sV;
  68409. brightOffsets[4] = -0.5 * sU;
  68410. brightOffsets[5] = -0.5 * sV;
  68411. brightOffsets[6] = 0.5 * sU;
  68412. brightOffsets[7] = -0.5 * sV;
  68413. effect.setArray2("dsOffsets", brightOffsets);
  68414. effect.setFloat("brightThreshold", _this.brightThreshold);
  68415. };
  68416. // Add to pipeline
  68417. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  68418. };
  68419. // Create blur H&V post-processes
  68420. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  68421. var _this = this;
  68422. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  68423. var engine = scene.getEngine();
  68424. 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);
  68425. 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);
  68426. blurX.onActivateObservable.add(function () {
  68427. var dw = blurX.width / engine.getRenderWidth();
  68428. blurX.kernel = _this[blurWidthKey] * dw;
  68429. });
  68430. blurY.onActivateObservable.add(function () {
  68431. var dw = blurY.height / engine.getRenderHeight();
  68432. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  68433. });
  68434. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  68435. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  68436. this.blurHPostProcesses.push(blurX);
  68437. this.blurVPostProcesses.push(blurY);
  68438. };
  68439. // Create texture adder post-process
  68440. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  68441. var _this = this;
  68442. 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);
  68443. this.textureAdderPostProcess.onApply = function (effect) {
  68444. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  68445. effect.setTexture("lensSampler", _this.lensTexture);
  68446. effect.setFloat("exposure", _this.exposure);
  68447. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  68448. };
  68449. // Add to pipeline
  68450. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  68451. };
  68452. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  68453. var _this = this;
  68454. var geometryRenderer = scene.enableGeometryBufferRenderer();
  68455. geometryRenderer.enablePosition = true;
  68456. var geometry = geometryRenderer.getGBuffer();
  68457. // Base post-process
  68458. 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));
  68459. var depthValues = BABYLON.Vector2.Zero();
  68460. this.volumetricLightPostProcess.onApply = function (effect) {
  68461. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  68462. var generator = _this.sourceLight.getShadowGenerator();
  68463. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  68464. effect.setTexture("positionSampler", geometry.textures[2]);
  68465. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  68466. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  68467. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  68468. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  68469. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  68470. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  68471. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  68472. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  68473. effect.setVector2("depthValues", depthValues);
  68474. }
  68475. };
  68476. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  68477. // Smooth
  68478. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  68479. // Merge
  68480. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  68481. this.volumetricLightMergePostProces.onApply = function (effect) {
  68482. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  68483. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  68484. };
  68485. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  68486. };
  68487. // Create luminance
  68488. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  68489. var _this = this;
  68490. // Create luminance
  68491. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  68492. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  68493. var offsets = [];
  68494. this.luminancePostProcess.onApply = function (effect) {
  68495. var sU = (1.0 / _this.luminancePostProcess.width);
  68496. var sV = (1.0 / _this.luminancePostProcess.height);
  68497. offsets[0] = -0.5 * sU;
  68498. offsets[1] = 0.5 * sV;
  68499. offsets[2] = 0.5 * sU;
  68500. offsets[3] = 0.5 * sV;
  68501. offsets[4] = -0.5 * sU;
  68502. offsets[5] = -0.5 * sV;
  68503. offsets[6] = 0.5 * sU;
  68504. offsets[7] = -0.5 * sV;
  68505. effect.setArray2("lumOffsets", offsets);
  68506. };
  68507. // Add to pipeline
  68508. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  68509. // Create down sample luminance
  68510. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  68511. var size = Math.pow(3, i);
  68512. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  68513. if (i === 0) {
  68514. defines += "#define FINAL_DOWN_SAMPLER";
  68515. }
  68516. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  68517. this.luminanceDownSamplePostProcesses.push(postProcess);
  68518. }
  68519. // Create callbacks and add effects
  68520. var lastLuminance = this.luminancePostProcess;
  68521. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  68522. var downSampleOffsets = new Array(18);
  68523. pp.onApply = function (effect) {
  68524. if (!lastLuminance) {
  68525. return;
  68526. }
  68527. var id = 0;
  68528. for (var x = -1; x < 2; x++) {
  68529. for (var y = -1; y < 2; y++) {
  68530. downSampleOffsets[id] = x / lastLuminance.width;
  68531. downSampleOffsets[id + 1] = y / lastLuminance.height;
  68532. id += 2;
  68533. }
  68534. }
  68535. effect.setArray2("dsOffsets", downSampleOffsets);
  68536. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  68537. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  68538. lastLuminance = _this.luminancePostProcess;
  68539. }
  68540. else {
  68541. lastLuminance = pp;
  68542. }
  68543. };
  68544. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  68545. pp.onAfterRender = function (effect) {
  68546. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  68547. 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);
  68548. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  68549. };
  68550. }
  68551. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  68552. });
  68553. };
  68554. // Create HDR post-process
  68555. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  68556. var _this = this;
  68557. 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);
  68558. var outputLiminance = 1;
  68559. var time = 0;
  68560. var lastTime = 0;
  68561. this.hdrPostProcess.onApply = function (effect) {
  68562. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  68563. time += scene.getEngine().getDeltaTime();
  68564. if (outputLiminance < 0) {
  68565. outputLiminance = _this._hdrCurrentLuminance;
  68566. }
  68567. else {
  68568. var dt = (lastTime - time) / 1000.0;
  68569. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  68570. outputLiminance += _this.hdrDecreaseRate * dt;
  68571. }
  68572. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  68573. outputLiminance -= _this.hdrIncreaseRate * dt;
  68574. }
  68575. else {
  68576. outputLiminance = _this._hdrCurrentLuminance;
  68577. }
  68578. }
  68579. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  68580. effect.setFloat("averageLuminance", outputLiminance);
  68581. lastTime = time;
  68582. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  68583. };
  68584. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  68585. };
  68586. // Create lens flare post-process
  68587. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  68588. var _this = this;
  68589. 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);
  68590. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  68591. this._createBlurPostProcesses(scene, ratio / 4, 2);
  68592. 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);
  68593. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  68594. var resolution = new BABYLON.Vector2(0, 0);
  68595. // Lens flare
  68596. this.lensFlarePostProcess.onApply = function (effect) {
  68597. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  68598. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  68599. effect.setFloat("strength", _this.lensFlareStrength);
  68600. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  68601. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  68602. // Shift
  68603. resolution.x = _this.lensFlarePostProcess.width;
  68604. resolution.y = _this.lensFlarePostProcess.height;
  68605. effect.setVector2("resolution", resolution);
  68606. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  68607. };
  68608. // Compose
  68609. 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);
  68610. 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);
  68611. this.lensFlareComposePostProcess.onApply = function (effect) {
  68612. if (!_this._scene.activeCamera) {
  68613. return;
  68614. }
  68615. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  68616. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  68617. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  68618. // Lens start rotation matrix
  68619. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  68620. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  68621. 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));
  68622. camRot *= 4.0;
  68623. 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);
  68624. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  68625. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  68626. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  68627. };
  68628. };
  68629. // Create depth-of-field post-process
  68630. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  68631. var _this = this;
  68632. 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);
  68633. this.depthOfFieldPostProcess.onApply = function (effect) {
  68634. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  68635. effect.setTexture("depthSampler", _this._getDepthTexture());
  68636. effect.setFloat("distance", _this.depthOfFieldDistance);
  68637. };
  68638. // Add to pipeline
  68639. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  68640. };
  68641. // Create motion blur post-process
  68642. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  68643. var _this = this;
  68644. 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);
  68645. var motionScale = 0;
  68646. var prevViewProjection = BABYLON.Matrix.Identity();
  68647. var invViewProjection = BABYLON.Matrix.Identity();
  68648. var viewProjection = BABYLON.Matrix.Identity();
  68649. var screenSize = BABYLON.Vector2.Zero();
  68650. this.motionBlurPostProcess.onApply = function (effect) {
  68651. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  68652. viewProjection.invertToRef(invViewProjection);
  68653. effect.setMatrix("inverseViewProjection", invViewProjection);
  68654. effect.setMatrix("prevViewProjection", prevViewProjection);
  68655. prevViewProjection = viewProjection;
  68656. screenSize.x = _this.motionBlurPostProcess.width;
  68657. screenSize.y = _this.motionBlurPostProcess.height;
  68658. effect.setVector2("screenSize", screenSize);
  68659. motionScale = scene.getEngine().getFps() / 60.0;
  68660. effect.setFloat("motionScale", motionScale);
  68661. effect.setFloat("motionStrength", _this.motionStrength);
  68662. effect.setTexture("depthSampler", _this._getDepthTexture());
  68663. };
  68664. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  68665. };
  68666. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  68667. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  68668. var renderer = this._scene.enableGeometryBufferRenderer();
  68669. return renderer.getGBuffer().textures[0];
  68670. }
  68671. return this._scene.enableDepthRenderer().getDepthMap();
  68672. };
  68673. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  68674. for (var i = 0; i < this._cameras.length; i++) {
  68675. var camera = this._cameras[i];
  68676. if (this.originalPostProcess) {
  68677. this.originalPostProcess.dispose(camera);
  68678. }
  68679. if (this.downSampleX4PostProcess) {
  68680. this.downSampleX4PostProcess.dispose(camera);
  68681. }
  68682. if (this.brightPassPostProcess) {
  68683. this.brightPassPostProcess.dispose(camera);
  68684. }
  68685. if (this.textureAdderPostProcess) {
  68686. this.textureAdderPostProcess.dispose(camera);
  68687. }
  68688. if (this.textureAdderFinalPostProcess) {
  68689. this.textureAdderFinalPostProcess.dispose(camera);
  68690. }
  68691. if (this.volumetricLightPostProcess) {
  68692. this.volumetricLightPostProcess.dispose(camera);
  68693. }
  68694. if (this.volumetricLightSmoothXPostProcess) {
  68695. this.volumetricLightSmoothXPostProcess.dispose(camera);
  68696. }
  68697. if (this.volumetricLightSmoothYPostProcess) {
  68698. this.volumetricLightSmoothYPostProcess.dispose(camera);
  68699. }
  68700. if (this.volumetricLightMergePostProces) {
  68701. this.volumetricLightMergePostProces.dispose(camera);
  68702. }
  68703. if (this.volumetricLightFinalPostProcess) {
  68704. this.volumetricLightFinalPostProcess.dispose(camera);
  68705. }
  68706. if (this.lensFlarePostProcess) {
  68707. this.lensFlarePostProcess.dispose(camera);
  68708. }
  68709. if (this.lensFlareComposePostProcess) {
  68710. this.lensFlareComposePostProcess.dispose(camera);
  68711. }
  68712. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  68713. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  68714. }
  68715. if (this.luminancePostProcess) {
  68716. this.luminancePostProcess.dispose(camera);
  68717. }
  68718. if (this.hdrPostProcess) {
  68719. this.hdrPostProcess.dispose(camera);
  68720. }
  68721. if (this.hdrFinalPostProcess) {
  68722. this.hdrFinalPostProcess.dispose(camera);
  68723. }
  68724. if (this.depthOfFieldPostProcess) {
  68725. this.depthOfFieldPostProcess.dispose(camera);
  68726. }
  68727. if (this.motionBlurPostProcess) {
  68728. this.motionBlurPostProcess.dispose(camera);
  68729. }
  68730. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  68731. this.blurHPostProcesses[j].dispose(camera);
  68732. }
  68733. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  68734. this.blurVPostProcesses[j].dispose(camera);
  68735. }
  68736. }
  68737. this.originalPostProcess = null;
  68738. this.downSampleX4PostProcess = null;
  68739. this.brightPassPostProcess = null;
  68740. this.textureAdderPostProcess = null;
  68741. this.textureAdderFinalPostProcess = null;
  68742. this.volumetricLightPostProcess = null;
  68743. this.volumetricLightSmoothXPostProcess = null;
  68744. this.volumetricLightSmoothYPostProcess = null;
  68745. this.volumetricLightMergePostProces = null;
  68746. this.volumetricLightFinalPostProcess = null;
  68747. this.lensFlarePostProcess = null;
  68748. this.lensFlareComposePostProcess = null;
  68749. this.luminancePostProcess = null;
  68750. this.hdrPostProcess = null;
  68751. this.hdrFinalPostProcess = null;
  68752. this.depthOfFieldPostProcess = null;
  68753. this.motionBlurPostProcess = null;
  68754. this.luminanceDownSamplePostProcesses = [];
  68755. this.blurHPostProcesses = [];
  68756. this.blurVPostProcesses = [];
  68757. };
  68758. // Dispose
  68759. StandardRenderingPipeline.prototype.dispose = function () {
  68760. this._disposePostProcesses();
  68761. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  68762. _super.prototype.dispose.call(this);
  68763. };
  68764. // Serialize rendering pipeline
  68765. StandardRenderingPipeline.prototype.serialize = function () {
  68766. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  68767. serializationObject.customType = "StandardRenderingPipeline";
  68768. return serializationObject;
  68769. };
  68770. /**
  68771. * Static members
  68772. */
  68773. // Parse serialized pipeline
  68774. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  68775. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  68776. };
  68777. // Luminance steps
  68778. StandardRenderingPipeline.LuminanceSteps = 6;
  68779. __decorate([
  68780. BABYLON.serialize()
  68781. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  68782. __decorate([
  68783. BABYLON.serialize()
  68784. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  68785. __decorate([
  68786. BABYLON.serialize()
  68787. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  68788. __decorate([
  68789. BABYLON.serialize()
  68790. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  68791. __decorate([
  68792. BABYLON.serializeAsTexture("lensTexture")
  68793. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  68794. __decorate([
  68795. BABYLON.serialize()
  68796. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  68797. __decorate([
  68798. BABYLON.serialize()
  68799. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  68800. __decorate([
  68801. BABYLON.serialize()
  68802. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  68803. __decorate([
  68804. BABYLON.serialize()
  68805. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  68806. __decorate([
  68807. BABYLON.serialize()
  68808. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  68809. __decorate([
  68810. BABYLON.serialize()
  68811. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  68812. __decorate([
  68813. BABYLON.serializeAsTexture("lensColorTexture")
  68814. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  68815. __decorate([
  68816. BABYLON.serialize()
  68817. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  68818. __decorate([
  68819. BABYLON.serialize()
  68820. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  68821. __decorate([
  68822. BABYLON.serialize()
  68823. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  68824. __decorate([
  68825. BABYLON.serialize()
  68826. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  68827. __decorate([
  68828. BABYLON.serializeAsTexture("lensStarTexture")
  68829. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  68830. __decorate([
  68831. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  68832. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  68833. __decorate([
  68834. BABYLON.serialize()
  68835. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  68836. __decorate([
  68837. BABYLON.serialize()
  68838. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  68839. __decorate([
  68840. BABYLON.serialize()
  68841. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  68842. __decorate([
  68843. BABYLON.serialize()
  68844. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  68845. __decorate([
  68846. BABYLON.serialize()
  68847. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  68848. __decorate([
  68849. BABYLON.serialize()
  68850. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  68851. __decorate([
  68852. BABYLON.serialize()
  68853. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  68854. __decorate([
  68855. BABYLON.serialize()
  68856. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  68857. __decorate([
  68858. BABYLON.serialize()
  68859. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  68860. __decorate([
  68861. BABYLON.serialize()
  68862. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  68863. __decorate([
  68864. BABYLON.serialize()
  68865. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  68866. __decorate([
  68867. BABYLON.serialize()
  68868. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  68869. return StandardRenderingPipeline;
  68870. }(BABYLON.PostProcessRenderPipeline));
  68871. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  68872. })(BABYLON || (BABYLON = {}));
  68873. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  68874. "use strict";
  68875. var BABYLON;
  68876. (function (BABYLON) {
  68877. var FxaaPostProcess = /** @class */ (function (_super) {
  68878. __extends(FxaaPostProcess, _super);
  68879. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  68880. if (camera === void 0) { camera = null; }
  68881. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68882. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  68883. _this.onApplyObservable.add(function (effect) {
  68884. var texelSize = _this.texelSize;
  68885. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  68886. });
  68887. return _this;
  68888. }
  68889. return FxaaPostProcess;
  68890. }(BABYLON.PostProcess));
  68891. BABYLON.FxaaPostProcess = FxaaPostProcess;
  68892. })(BABYLON || (BABYLON = {}));
  68893. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  68894. "use strict";
  68895. var BABYLON;
  68896. (function (BABYLON) {
  68897. /**
  68898. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  68899. */
  68900. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  68901. __extends(ChromaticAberrationPostProcess, _super);
  68902. /**
  68903. * Creates a new instance of @see ChromaticAberrationPostProcess
  68904. * @param name The name of the effect.
  68905. * @param screenWidth The width of the screen to apply the effect on.
  68906. * @param screenHeight The height of the screen to apply the effect on.
  68907. * @param options The required width/height ratio to downsize to before computing the render pass.
  68908. * @param camera The camera to apply the render pass to.
  68909. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68910. * @param engine The engine which the post process will be applied. (default: current engine)
  68911. * @param reusable If the post process can be reused on the same frame. (default: false)
  68912. * @param textureType Type of textures used when performing the post process. (default: 0)
  68913. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  68914. */
  68915. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  68916. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68917. if (blockCompilation === void 0) { blockCompilation = false; }
  68918. var _this = _super.call(this, name, "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  68919. /**
  68920. * The amount of seperation of rgb channels (default: 30)
  68921. */
  68922. _this.aberrationAmount = 30;
  68923. /**
  68924. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  68925. */
  68926. _this.radialIntensity = 0;
  68927. /**
  68928. * The normilized direction in which the rgb channels should be seperated. If set to 0,0 radial direction will be used. (default: Vector2(0.707,0.707))
  68929. */
  68930. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  68931. /**
  68932. * The center position where the radialIntensity should be around. [0.5,0.5 is center of screen, 1,1 is top right corder] (default: Vector2(0.5 ,0.5))
  68933. */
  68934. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  68935. _this.onApplyObservable.add(function (effect) {
  68936. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  68937. effect.setFloat('screen_width', screenWidth);
  68938. effect.setFloat('screen_height', screenHeight);
  68939. effect.setFloat('radialIntensity', _this.radialIntensity);
  68940. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  68941. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  68942. });
  68943. return _this;
  68944. }
  68945. return ChromaticAberrationPostProcess;
  68946. }(BABYLON.PostProcess));
  68947. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  68948. })(BABYLON || (BABYLON = {}));
  68949. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  68950. "use strict";
  68951. var BABYLON;
  68952. (function (BABYLON) {
  68953. /**
  68954. * The SharpenPostProcess applies a sharpen kernel to every pixel
  68955. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  68956. */
  68957. var SharpenPostProcess = /** @class */ (function (_super) {
  68958. __extends(SharpenPostProcess, _super);
  68959. /**
  68960. * Creates a new instance of @see ConvolutionPostProcess
  68961. * @param name The name of the effect.
  68962. * @param options The required width/height ratio to downsize to before computing the render pass.
  68963. * @param camera The camera to apply the render pass to.
  68964. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68965. * @param engine The engine which the post process will be applied. (default: current engine)
  68966. * @param reusable If the post process can be reused on the same frame. (default: false)
  68967. * @param textureType Type of textures used when performing the post process. (default: 0)
  68968. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  68969. */
  68970. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  68971. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68972. if (blockCompilation === void 0) { blockCompilation = false; }
  68973. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  68974. /**
  68975. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  68976. */
  68977. _this.colorAmount = 1.0;
  68978. /**
  68979. * How much sharpness should be applied (default: 0.3)
  68980. */
  68981. _this.edgeAmount = 0.3;
  68982. _this.onApply = function (effect) {
  68983. effect.setFloat2("screenSize", _this.width, _this.height);
  68984. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  68985. };
  68986. return _this;
  68987. }
  68988. return SharpenPostProcess;
  68989. }(BABYLON.PostProcess));
  68990. BABYLON.SharpenPostProcess = SharpenPostProcess;
  68991. })(BABYLON || (BABYLON = {}));
  68992. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  68993. "use strict";
  68994. var BABYLON;
  68995. (function (BABYLON) {
  68996. /**
  68997. * The Blur Post Process which blurs an image based on a kernel and direction.
  68998. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  68999. */
  69000. var BlurPostProcess = /** @class */ (function (_super) {
  69001. __extends(BlurPostProcess, _super);
  69002. /**
  69003. * Creates a new instance of @see BlurPostProcess
  69004. * @param name The name of the effect.
  69005. * @param direction The direction in which to blur the image.
  69006. * @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.
  69007. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  69008. * @param camera The camera to apply the render pass to.
  69009. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69010. * @param engine The engine which the post process will be applied. (default: current engine)
  69011. * @param reusable If the post process can be reused on the same frame. (default: false)
  69012. * @param textureType Type of textures used when performing the post process. (default: 0)
  69013. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69014. */
  69015. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  69016. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69017. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69018. if (defines === void 0) { defines = ""; }
  69019. if (blockCompilation === void 0) { blockCompilation = false; }
  69020. 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;
  69021. _this.direction = direction;
  69022. _this.blockCompilation = blockCompilation;
  69023. _this._packedFloat = false;
  69024. _this._staticDefines = "";
  69025. _this._staticDefines = defines;
  69026. _this.onApplyObservable.add(function (effect) {
  69027. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  69028. });
  69029. _this.kernel = kernel;
  69030. return _this;
  69031. }
  69032. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  69033. /**
  69034. * Gets the length in pixels of the blur sample region
  69035. */
  69036. get: function () {
  69037. return this._idealKernel;
  69038. },
  69039. /**
  69040. * Sets the length in pixels of the blur sample region
  69041. */
  69042. set: function (v) {
  69043. if (this._idealKernel === v) {
  69044. return;
  69045. }
  69046. v = Math.max(v, 1);
  69047. this._idealKernel = v;
  69048. this._kernel = this._nearestBestKernel(v);
  69049. if (!this.blockCompilation) {
  69050. this._updateParameters();
  69051. }
  69052. },
  69053. enumerable: true,
  69054. configurable: true
  69055. });
  69056. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  69057. /**
  69058. * Gets wether or not the blur is unpacking/repacking floats
  69059. */
  69060. get: function () {
  69061. return this._packedFloat;
  69062. },
  69063. /**
  69064. * Sets wether or not the blur needs to unpack/repack floats
  69065. */
  69066. set: function (v) {
  69067. if (this._packedFloat === v) {
  69068. return;
  69069. }
  69070. this._packedFloat = v;
  69071. if (!this.blockCompilation) {
  69072. this._updateParameters();
  69073. }
  69074. },
  69075. enumerable: true,
  69076. configurable: true
  69077. });
  69078. /**
  69079. * Updates the effect with the current post process compile time values and recompiles the shader.
  69080. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  69081. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  69082. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  69083. * @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
  69084. * @param onCompiled Called when the shader has been compiled.
  69085. * @param onError Called if there is an error when compiling a shader.
  69086. */
  69087. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  69088. if (defines === void 0) { defines = null; }
  69089. if (uniforms === void 0) { uniforms = null; }
  69090. if (samplers === void 0) { samplers = null; }
  69091. this._updateParameters(onCompiled, onError);
  69092. };
  69093. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  69094. // Generate sampling offsets and weights
  69095. var N = this._kernel;
  69096. var centerIndex = (N - 1) / 2;
  69097. // Generate Gaussian sampling weights over kernel
  69098. var offsets = [];
  69099. var weights = [];
  69100. var totalWeight = 0;
  69101. for (var i = 0; i < N; i++) {
  69102. var u = i / (N - 1);
  69103. var w = this._gaussianWeight(u * 2.0 - 1);
  69104. offsets[i] = (i - centerIndex);
  69105. weights[i] = w;
  69106. totalWeight += w;
  69107. }
  69108. // Normalize weights
  69109. for (var i = 0; i < weights.length; i++) {
  69110. weights[i] /= totalWeight;
  69111. }
  69112. // Optimize: combine samples to take advantage of hardware linear sampling
  69113. // Walk from left to center, combining pairs (symmetrically)
  69114. var linearSamplingWeights = [];
  69115. var linearSamplingOffsets = [];
  69116. var linearSamplingMap = [];
  69117. for (var i = 0; i <= centerIndex; i += 2) {
  69118. var j = Math.min(i + 1, Math.floor(centerIndex));
  69119. var singleCenterSample = i === j;
  69120. if (singleCenterSample) {
  69121. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69122. }
  69123. else {
  69124. var sharedCell = j === centerIndex;
  69125. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  69126. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  69127. if (offsetLinear === 0) {
  69128. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69129. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  69130. }
  69131. else {
  69132. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  69133. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  69134. }
  69135. }
  69136. }
  69137. for (var i = 0; i < linearSamplingMap.length; i++) {
  69138. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  69139. linearSamplingWeights[i] = linearSamplingMap[i].w;
  69140. }
  69141. // Replace with optimized
  69142. offsets = linearSamplingOffsets;
  69143. weights = linearSamplingWeights;
  69144. // Generate shaders
  69145. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  69146. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  69147. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  69148. var defines = "";
  69149. defines += this._staticDefines;
  69150. for (var i = 0; i < varyingCount; i++) {
  69151. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  69152. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  69153. }
  69154. var depCount = 0;
  69155. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  69156. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  69157. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  69158. depCount++;
  69159. }
  69160. if (this.packedFloat) {
  69161. defines += "#define PACKEDFLOAT 1";
  69162. }
  69163. _super.prototype.updateEffect.call(this, defines, null, null, {
  69164. varyingCount: varyingCount,
  69165. depCount: depCount
  69166. }, onCompiled, onError);
  69167. };
  69168. /**
  69169. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  69170. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  69171. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  69172. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  69173. * The gaps between physical kernels are compensated for in the weighting of the samples
  69174. * @param idealKernel Ideal blur kernel.
  69175. * @return Nearest best kernel.
  69176. */
  69177. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  69178. var v = Math.round(idealKernel);
  69179. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  69180. var k = _a[_i];
  69181. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  69182. return Math.max(k, 3);
  69183. }
  69184. }
  69185. return Math.max(v, 3);
  69186. };
  69187. /**
  69188. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  69189. * @param x The point on the Gaussian distribution to sample.
  69190. * @return the value of the Gaussian function at x.
  69191. */
  69192. BlurPostProcess.prototype._gaussianWeight = function (x) {
  69193. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  69194. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  69195. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  69196. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  69197. // truncated at around 1.3% of peak strength.
  69198. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  69199. var sigma = (1 / 3);
  69200. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  69201. var exponent = -((x * x) / (2.0 * sigma * sigma));
  69202. var weight = (1.0 / denominator) * Math.exp(exponent);
  69203. return weight;
  69204. };
  69205. /**
  69206. * Generates a string that can be used as a floating point number in GLSL.
  69207. * @param x Value to print.
  69208. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  69209. * @return GLSL float string.
  69210. */
  69211. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  69212. if (decimalFigures === void 0) { decimalFigures = 8; }
  69213. return x.toFixed(decimalFigures).replace(/0+$/, '');
  69214. };
  69215. return BlurPostProcess;
  69216. }(BABYLON.PostProcess));
  69217. BABYLON.BlurPostProcess = BlurPostProcess;
  69218. })(BABYLON || (BABYLON = {}));
  69219. //# sourceMappingURL=babylon.blurPostProcess.js.map
  69220. "use strict";
  69221. var BABYLON;
  69222. (function (BABYLON) {
  69223. /**
  69224. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  69225. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  69226. * based on samples that have a large difference in distance than the center pixel.
  69227. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  69228. */
  69229. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  69230. __extends(DepthOfFieldBlurPostProcess, _super);
  69231. /**
  69232. * Creates a new instance of @see CircleOfConfusionPostProcess
  69233. * @param name The name of the effect.
  69234. * @param scene The scene the effect belongs to.
  69235. * @param direction The direction the blur should be applied.
  69236. * @param kernel The size of the kernel used to blur.
  69237. * @param options The required width/height ratio to downsize to before computing the render pass.
  69238. * @param camera The camera to apply the render pass to.
  69239. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  69240. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  69241. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69242. * @param engine The engine which the post process will be applied. (default: current engine)
  69243. * @param reusable If the post process can be reused on the same frame. (default: false)
  69244. * @param textureType Type of textures used when performing the post process. (default: 0)
  69245. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69246. */
  69247. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  69248. if (imageToBlur === void 0) { imageToBlur = null; }
  69249. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69250. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69251. if (blockCompilation === void 0) { blockCompilation = false; }
  69252. var _this = _super.call(this, name, direction, kernel, options, camera, samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, "#define DOF 1\r\n", blockCompilation) || this;
  69253. _this.direction = direction;
  69254. _this.onApplyObservable.add(function (effect) {
  69255. if (imageToBlur != null) {
  69256. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  69257. }
  69258. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  69259. if (scene.activeCamera) {
  69260. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  69261. }
  69262. });
  69263. return _this;
  69264. }
  69265. return DepthOfFieldBlurPostProcess;
  69266. }(BABYLON.BlurPostProcess));
  69267. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  69268. })(BABYLON || (BABYLON = {}));
  69269. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  69270. "use strict";
  69271. var BABYLON;
  69272. (function (BABYLON) {
  69273. /**
  69274. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  69275. */
  69276. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  69277. __extends(DepthOfFieldMergePostProcess, _super);
  69278. /**
  69279. * Creates a new instance of @see CircleOfConfusionPostProcess
  69280. * @param name The name of the effect.
  69281. * @param original The non-blurred image to be modified
  69282. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  69283. * @param blurSteps Incrimental bluring post processes.
  69284. * @param options The required width/height ratio to downsize to before computing the render pass.
  69285. * @param camera The camera to apply the render pass to.
  69286. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69287. * @param engine The engine which the post process will be applied. (default: current engine)
  69288. * @param reusable If the post process can be reused on the same frame. (default: false)
  69289. * @param textureType Type of textures used when performing the post process. (default: 0)
  69290. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69291. */
  69292. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69293. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69294. if (blockCompilation === void 0) { blockCompilation = false; }
  69295. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  69296. _this.blurSteps = blurSteps;
  69297. _this.onApplyObservable.add(function (effect) {
  69298. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  69299. effect.setTextureFromPostProcess("textureSampler", original);
  69300. blurSteps.forEach(function (step, index) {
  69301. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  69302. });
  69303. });
  69304. if (!blockCompilation) {
  69305. _this.updateEffect();
  69306. }
  69307. return _this;
  69308. }
  69309. /**
  69310. * Updates the effect with the current post process compile time values and recompiles the shader.
  69311. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  69312. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  69313. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  69314. * @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
  69315. * @param onCompiled Called when the shader has been compiled.
  69316. * @param onError Called if there is an error when compiling a shader.
  69317. */
  69318. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  69319. if (defines === void 0) { defines = null; }
  69320. if (uniforms === void 0) { uniforms = null; }
  69321. if (samplers === void 0) { samplers = null; }
  69322. _super.prototype.updateEffect.call(this, defines ? defines : "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n", uniforms, samplers, indexParameters, onCompiled, onError);
  69323. };
  69324. return DepthOfFieldMergePostProcess;
  69325. }(BABYLON.PostProcess));
  69326. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  69327. })(BABYLON || (BABYLON = {}));
  69328. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  69329. "use strict";
  69330. var BABYLON;
  69331. (function (BABYLON) {
  69332. /**
  69333. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  69334. */
  69335. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  69336. __extends(CircleOfConfusionPostProcess, _super);
  69337. /**
  69338. * Creates a new instance of @see CircleOfConfusionPostProcess
  69339. * @param name The name of the effect.
  69340. * @param depthTexture The depth texture of the scene to compute the circle of confusion. This must be set in order for this to function but may be set after initialization if needed.
  69341. * @param options The required width/height ratio to downsize to before computing the render pass.
  69342. * @param camera The camera to apply the render pass to.
  69343. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69344. * @param engine The engine which the post process will be applied. (default: current engine)
  69345. * @param reusable If the post process can be reused on the same frame. (default: false)
  69346. * @param textureType Type of textures used when performing the post process. (default: 0)
  69347. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69348. */
  69349. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69350. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69351. if (blockCompilation === void 0) { blockCompilation = false; }
  69352. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  69353. /**
  69354. * 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.
  69355. */
  69356. _this.lensSize = 50;
  69357. /**
  69358. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  69359. */
  69360. _this.fStop = 1.4;
  69361. /**
  69362. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  69363. */
  69364. _this.focusDistance = 2000;
  69365. /**
  69366. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  69367. */
  69368. _this.focalLength = 50;
  69369. _this._depthTexture = null;
  69370. _this._depthTexture = depthTexture;
  69371. _this.onApplyObservable.add(function (effect) {
  69372. if (!_this._depthTexture) {
  69373. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  69374. return;
  69375. }
  69376. effect.setTexture("depthSampler", _this._depthTexture);
  69377. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  69378. var aperture = _this.lensSize / _this.fStop;
  69379. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  69380. effect.setFloat('focusDistance', _this.focusDistance);
  69381. effect.setFloat('cocPrecalculation', cocPrecalculation);
  69382. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  69383. });
  69384. return _this;
  69385. }
  69386. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  69387. /**
  69388. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  69389. */
  69390. set: function (value) {
  69391. this._depthTexture = value;
  69392. },
  69393. enumerable: true,
  69394. configurable: true
  69395. });
  69396. return CircleOfConfusionPostProcess;
  69397. }(BABYLON.PostProcess));
  69398. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  69399. })(BABYLON || (BABYLON = {}));
  69400. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  69401. "use strict";
  69402. var BABYLON;
  69403. (function (BABYLON) {
  69404. /**
  69405. * Specifies the level of max blur that should be applied when using the depth of field effect
  69406. */
  69407. var DepthOfFieldEffectBlurLevel;
  69408. (function (DepthOfFieldEffectBlurLevel) {
  69409. /**
  69410. * Subtle blur
  69411. */
  69412. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  69413. /**
  69414. * Medium blur
  69415. */
  69416. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  69417. /**
  69418. * Large blur
  69419. */
  69420. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  69421. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  69422. ;
  69423. /**
  69424. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  69425. */
  69426. var DepthOfFieldEffect = /** @class */ (function (_super) {
  69427. __extends(DepthOfFieldEffect, _super);
  69428. /**
  69429. * Creates a new instance of @see DepthOfFieldEffect
  69430. * @param scene The scene the effect belongs to.
  69431. * @param depthTexture The depth texture of the scene to compute the circle of confusion.This must be set in order for this to function but may be set after initialization if needed.
  69432. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  69433. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69434. */
  69435. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  69436. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  69437. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  69438. if (blockCompilation === void 0) { blockCompilation = false; }
  69439. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  69440. return _this._effects;
  69441. }, true) || this;
  69442. _this._effects = [];
  69443. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  69444. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69445. // 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)
  69446. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  69447. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  69448. _this._depthOfFieldBlurY = [];
  69449. _this._depthOfFieldBlurX = [];
  69450. var blurCount = 1;
  69451. var kernelSize = 15;
  69452. switch (blurLevel) {
  69453. case DepthOfFieldEffectBlurLevel.High: {
  69454. blurCount = 3;
  69455. kernelSize = 51;
  69456. break;
  69457. }
  69458. case DepthOfFieldEffectBlurLevel.Medium: {
  69459. blurCount = 2;
  69460. kernelSize = 31;
  69461. break;
  69462. }
  69463. default: {
  69464. kernelSize = 15;
  69465. blurCount = 1;
  69466. break;
  69467. }
  69468. }
  69469. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  69470. for (var i = 0; i < blurCount; i++) {
  69471. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69472. blurY.autoClear = false;
  69473. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69474. blurX.autoClear = false;
  69475. _this._depthOfFieldBlurY.push(blurY);
  69476. _this._depthOfFieldBlurX.push(blurX);
  69477. }
  69478. // Merge blurred images with original image based on circleOfConfusion
  69479. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69480. _this._depthOfFieldMerge.autoClear = false;
  69481. // Set all post processes on the effect.
  69482. _this._effects = [_this._circleOfConfusion];
  69483. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  69484. _this._effects.push(_this._depthOfFieldBlurY[i]);
  69485. _this._effects.push(_this._depthOfFieldBlurX[i]);
  69486. }
  69487. _this._effects.push(_this._depthOfFieldMerge);
  69488. return _this;
  69489. }
  69490. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  69491. get: function () {
  69492. return this._circleOfConfusion.focalLength;
  69493. },
  69494. /**
  69495. * The focal the length of the camera used in the effect
  69496. */
  69497. set: function (value) {
  69498. this._circleOfConfusion.focalLength = value;
  69499. },
  69500. enumerable: true,
  69501. configurable: true
  69502. });
  69503. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  69504. get: function () {
  69505. return this._circleOfConfusion.fStop;
  69506. },
  69507. /**
  69508. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  69509. */
  69510. set: function (value) {
  69511. this._circleOfConfusion.fStop = value;
  69512. },
  69513. enumerable: true,
  69514. configurable: true
  69515. });
  69516. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  69517. get: function () {
  69518. return this._circleOfConfusion.focusDistance;
  69519. },
  69520. /**
  69521. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  69522. */
  69523. set: function (value) {
  69524. this._circleOfConfusion.focusDistance = value;
  69525. },
  69526. enumerable: true,
  69527. configurable: true
  69528. });
  69529. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  69530. get: function () {
  69531. return this._circleOfConfusion.lensSize;
  69532. },
  69533. /**
  69534. * 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.
  69535. */
  69536. set: function (value) {
  69537. this._circleOfConfusion.lensSize = value;
  69538. },
  69539. enumerable: true,
  69540. configurable: true
  69541. });
  69542. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  69543. /**
  69544. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  69545. */
  69546. set: function (value) {
  69547. this._circleOfConfusion.depthTexture = value;
  69548. },
  69549. enumerable: true,
  69550. configurable: true
  69551. });
  69552. /**
  69553. * Disposes each of the internal effects for a given camera.
  69554. * @param camera The camera to dispose the effect on.
  69555. */
  69556. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  69557. this._circleOfConfusion.dispose(camera);
  69558. this._depthOfFieldBlurX.forEach(function (element) {
  69559. element.dispose(camera);
  69560. });
  69561. this._depthOfFieldBlurY.forEach(function (element) {
  69562. element.dispose(camera);
  69563. });
  69564. this._depthOfFieldMerge.dispose(camera);
  69565. };
  69566. /**
  69567. * Internal
  69568. */
  69569. DepthOfFieldEffect.prototype._updateEffects = function () {
  69570. for (var effect in this._effects) {
  69571. this._effects[effect].updateEffect();
  69572. }
  69573. };
  69574. /**
  69575. * Internal
  69576. * @returns if all the contained post processes are ready.
  69577. */
  69578. DepthOfFieldEffect.prototype._isReady = function () {
  69579. for (var effect in this._effects) {
  69580. if (!this._effects[effect].isReady()) {
  69581. return false;
  69582. }
  69583. }
  69584. return true;
  69585. };
  69586. return DepthOfFieldEffect;
  69587. }(BABYLON.PostProcessRenderEffect));
  69588. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  69589. })(BABYLON || (BABYLON = {}));
  69590. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  69591. "use strict";
  69592. var BABYLON;
  69593. (function (BABYLON) {
  69594. /**
  69595. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  69596. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  69597. */
  69598. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  69599. __extends(DefaultRenderingPipeline, _super);
  69600. /**
  69601. * @constructor
  69602. * @param {string} name - The rendering pipeline name
  69603. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  69604. * @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)
  69605. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  69606. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  69607. */
  69608. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  69609. if (automaticBuild === void 0) { automaticBuild = true; }
  69610. var _this = _super.call(this, scene.getEngine(), name) || this;
  69611. _this._originalCameras = [];
  69612. /**
  69613. * ID of the sharpen post process,
  69614. */
  69615. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  69616. /**
  69617. * ID of the pass post process used for bloom,
  69618. */
  69619. _this.PassPostProcessId = "PassPostProcessEffect";
  69620. /**
  69621. * ID of the highlight post process used for bloom,
  69622. */
  69623. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  69624. /**
  69625. * ID of the blurX post process used for bloom,
  69626. */
  69627. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  69628. /**
  69629. * ID of the blurY post process used for bloom,
  69630. */
  69631. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  69632. /**
  69633. * ID of the copy back post process used for bloom,
  69634. */
  69635. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  69636. /**
  69637. * ID of the image processing post process;
  69638. */
  69639. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  69640. /**
  69641. * ID of the Fast Approximate Anti-Aliasing post process;
  69642. */
  69643. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  69644. /**
  69645. * ID of the final merge post process;
  69646. */
  69647. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  69648. /**
  69649. * ID of the chromatic aberration post process,
  69650. */
  69651. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  69652. /**
  69653. * Animations which can be used to tweak settings over a period of time
  69654. */
  69655. _this.animations = [];
  69656. // Values
  69657. _this._sharpenEnabled = false;
  69658. _this._bloomEnabled = false;
  69659. _this._depthOfFieldEnabled = false;
  69660. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  69661. _this._fxaaEnabled = false;
  69662. _this._msaaEnabled = false;
  69663. _this._imageProcessingEnabled = true;
  69664. _this._bloomScale = 0.6;
  69665. _this._chromaticAberrationEnabled = false;
  69666. _this._buildAllowed = true;
  69667. /**
  69668. * Specifies the size of the bloom blur kernel, relative to the final output size
  69669. */
  69670. _this.bloomKernel = 64;
  69671. /**
  69672. * Specifies the weight of the bloom in the final rendering
  69673. */
  69674. _this._bloomWeight = 0.15;
  69675. _this._prevPostProcess = null;
  69676. _this._prevPrevPostProcess = null;
  69677. _this._cameras = cameras || [];
  69678. _this._originalCameras = _this._cameras.slice();
  69679. _this._buildAllowed = automaticBuild;
  69680. // Initialize
  69681. _this._scene = scene;
  69682. var caps = _this._scene.getEngine().getCaps();
  69683. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  69684. // Misc
  69685. if (_this._hdr) {
  69686. if (caps.textureHalfFloatRender) {
  69687. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69688. }
  69689. else if (caps.textureFloatRender) {
  69690. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69691. }
  69692. }
  69693. else {
  69694. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69695. }
  69696. // Attach
  69697. scene.postProcessRenderPipelineManager.addPipeline(_this);
  69698. var engine = _this._scene.getEngine();
  69699. // Create post processes before hand so they can be modified before enabled.
  69700. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  69701. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  69702. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  69703. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  69704. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  69705. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  69706. _this._buildPipeline();
  69707. return _this;
  69708. }
  69709. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  69710. get: function () {
  69711. return this._sharpenEnabled;
  69712. },
  69713. /**
  69714. * Enable or disable the sharpen process from the pipeline
  69715. */
  69716. set: function (enabled) {
  69717. if (this._sharpenEnabled === enabled) {
  69718. return;
  69719. }
  69720. this._sharpenEnabled = enabled;
  69721. this._buildPipeline();
  69722. },
  69723. enumerable: true,
  69724. configurable: true
  69725. });
  69726. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  69727. get: function () {
  69728. return this._bloomWeight;
  69729. },
  69730. /**
  69731. * The strength of the bloom.
  69732. */
  69733. set: function (value) {
  69734. if (this._bloomWeight === value) {
  69735. return;
  69736. }
  69737. this._bloomWeight = value;
  69738. if (this._hdr && this.copyBack) {
  69739. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  69740. }
  69741. },
  69742. enumerable: true,
  69743. configurable: true
  69744. });
  69745. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  69746. get: function () {
  69747. return this._bloomScale;
  69748. },
  69749. /**
  69750. * The scale of the bloom, lower value will provide better performance.
  69751. */
  69752. set: function (value) {
  69753. if (this._bloomScale === value) {
  69754. return;
  69755. }
  69756. this._bloomScale = value;
  69757. this._buildPipeline();
  69758. },
  69759. enumerable: true,
  69760. configurable: true
  69761. });
  69762. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  69763. get: function () {
  69764. return this._bloomEnabled;
  69765. },
  69766. /**
  69767. * Enable or disable the bloom from the pipeline
  69768. */
  69769. set: function (enabled) {
  69770. if (this._bloomEnabled === enabled) {
  69771. return;
  69772. }
  69773. this._bloomEnabled = enabled;
  69774. this._buildPipeline();
  69775. },
  69776. enumerable: true,
  69777. configurable: true
  69778. });
  69779. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  69780. /**
  69781. * If the depth of field is enabled.
  69782. */
  69783. get: function () {
  69784. return this._depthOfFieldEnabled;
  69785. },
  69786. set: function (enabled) {
  69787. if (this._depthOfFieldEnabled === enabled) {
  69788. return;
  69789. }
  69790. this._depthOfFieldEnabled = enabled;
  69791. this._buildPipeline();
  69792. },
  69793. enumerable: true,
  69794. configurable: true
  69795. });
  69796. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  69797. /**
  69798. * Blur level of the depth of field effect. (Higher blur will effect performance)
  69799. */
  69800. get: function () {
  69801. return this._depthOfFieldBlurLevel;
  69802. },
  69803. set: function (value) {
  69804. if (this._depthOfFieldBlurLevel === value) {
  69805. return;
  69806. }
  69807. this._depthOfFieldBlurLevel = value;
  69808. // recreate dof and dispose old as this setting is not dynamic
  69809. var oldDof = this.depthOfField;
  69810. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  69811. this.depthOfField.focalLength = oldDof.focalLength;
  69812. this.depthOfField.focusDistance = oldDof.focusDistance;
  69813. this.depthOfField.fStop = oldDof.fStop;
  69814. this.depthOfField.lensSize = oldDof.lensSize;
  69815. for (var i = 0; i < this._cameras.length; i++) {
  69816. oldDof.disposeEffects(this._cameras[i]);
  69817. }
  69818. this._buildPipeline();
  69819. },
  69820. enumerable: true,
  69821. configurable: true
  69822. });
  69823. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  69824. get: function () {
  69825. return this._fxaaEnabled;
  69826. },
  69827. /**
  69828. * If the anti aliasing is enabled.
  69829. */
  69830. set: function (enabled) {
  69831. if (this._fxaaEnabled === enabled) {
  69832. return;
  69833. }
  69834. this._fxaaEnabled = enabled;
  69835. this._buildPipeline();
  69836. },
  69837. enumerable: true,
  69838. configurable: true
  69839. });
  69840. Object.defineProperty(DefaultRenderingPipeline.prototype, "msaaEnabled", {
  69841. get: function () {
  69842. return this._msaaEnabled;
  69843. },
  69844. /**
  69845. * If the multisample anti-aliasing is enabled.
  69846. */
  69847. set: function (enabled) {
  69848. if (this._msaaEnabled === enabled) {
  69849. return;
  69850. }
  69851. this._msaaEnabled = enabled;
  69852. this._buildPipeline();
  69853. },
  69854. enumerable: true,
  69855. configurable: true
  69856. });
  69857. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  69858. get: function () {
  69859. return this._imageProcessingEnabled;
  69860. },
  69861. /**
  69862. * If image processing is enabled.
  69863. */
  69864. set: function (enabled) {
  69865. if (this._imageProcessingEnabled === enabled) {
  69866. return;
  69867. }
  69868. this._imageProcessingEnabled = enabled;
  69869. this._buildPipeline();
  69870. },
  69871. enumerable: true,
  69872. configurable: true
  69873. });
  69874. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  69875. get: function () {
  69876. return this._chromaticAberrationEnabled;
  69877. },
  69878. /**
  69879. * Enable or disable the chromaticAberration process from the pipeline
  69880. */
  69881. set: function (enabled) {
  69882. if (this._chromaticAberrationEnabled === enabled) {
  69883. return;
  69884. }
  69885. this._chromaticAberrationEnabled = enabled;
  69886. this._buildPipeline();
  69887. },
  69888. enumerable: true,
  69889. configurable: true
  69890. });
  69891. /**
  69892. * Force the compilation of the entire pipeline.
  69893. */
  69894. DefaultRenderingPipeline.prototype.prepare = function () {
  69895. var previousState = this._buildAllowed;
  69896. this._buildAllowed = true;
  69897. this._buildPipeline();
  69898. this._buildAllowed = previousState;
  69899. };
  69900. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  69901. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  69902. if (this._prevPostProcess && this._prevPostProcess.autoClear) {
  69903. postProcess.autoClear = false;
  69904. }
  69905. else {
  69906. postProcess.autoClear = true;
  69907. }
  69908. if (!skipTextureSharing) {
  69909. if (this._prevPrevPostProcess) {
  69910. postProcess.shareOutputWith(this._prevPrevPostProcess);
  69911. }
  69912. else {
  69913. postProcess.useOwnOutput();
  69914. }
  69915. if (this._prevPostProcess) {
  69916. this._prevPrevPostProcess = this._prevPostProcess;
  69917. }
  69918. this._prevPostProcess = postProcess;
  69919. }
  69920. };
  69921. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  69922. var _this = this;
  69923. if (!this._buildAllowed) {
  69924. return;
  69925. }
  69926. var engine = this._scene.getEngine();
  69927. this._disposePostProcesses();
  69928. if (this._cameras !== null) {
  69929. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69930. // get back cameras to be used to reattach pipeline
  69931. this._cameras = this._originalCameras.slice();
  69932. }
  69933. this._reset();
  69934. this._prevPostProcess = null;
  69935. this._prevPrevPostProcess = null;
  69936. if (this.sharpenEnabled) {
  69937. if (!this.sharpen.isReady()) {
  69938. this.sharpen.updateEffect();
  69939. }
  69940. this.addEffect(this._sharpenEffect);
  69941. this._setAutoClearAndTextureSharing(this.sharpen);
  69942. }
  69943. if (this.depthOfFieldEnabled) {
  69944. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  69945. this.depthOfField.depthTexture = depthTexture;
  69946. if (!this.depthOfField._isReady()) {
  69947. this.depthOfField._updateEffects();
  69948. }
  69949. this.addEffect(this.depthOfField);
  69950. this._setAutoClearAndTextureSharing(this.depthOfField._depthOfFieldMerge);
  69951. }
  69952. if (this.bloomEnabled) {
  69953. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69954. this._setAutoClearAndTextureSharing(this.pass, true);
  69955. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  69956. if (!this._hdr) {
  69957. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69958. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  69959. this.highlights.autoClear = false;
  69960. this.highlights.alwaysForcePOT = true;
  69961. }
  69962. 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);
  69963. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  69964. this.blurX.alwaysForcePOT = true;
  69965. this.blurX.autoClear = false;
  69966. this.blurX.onActivateObservable.add(function () {
  69967. var dw = _this.blurX.width / engine.getRenderWidth(true);
  69968. _this.blurX.kernel = _this.bloomKernel * dw;
  69969. });
  69970. 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);
  69971. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  69972. this.blurY.alwaysForcePOT = true;
  69973. this.blurY.autoClear = false;
  69974. this.blurY.onActivateObservable.add(function () {
  69975. var dh = _this.blurY.height / engine.getRenderHeight(true);
  69976. _this.blurY.kernel = _this.bloomKernel * dh;
  69977. });
  69978. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69979. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  69980. this.copyBack.alwaysForcePOT = true;
  69981. if (this._hdr) {
  69982. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  69983. var w = this.bloomWeight;
  69984. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  69985. }
  69986. else {
  69987. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  69988. }
  69989. this.copyBack.autoClear = false;
  69990. }
  69991. if (this._imageProcessingEnabled) {
  69992. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69993. if (this._hdr) {
  69994. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  69995. }
  69996. else {
  69997. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  69998. }
  69999. }
  70000. if (this._hdr && this.imageProcessing) {
  70001. this.finalMerge = this.imageProcessing;
  70002. }
  70003. else {
  70004. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70005. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  70006. this._setAutoClearAndTextureSharing(this.finalMerge, true);
  70007. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  70008. }
  70009. if (this.bloomEnabled) {
  70010. if (this._hdr) {
  70011. this.copyBack.shareOutputWith(this.blurX);
  70012. if (this.imageProcessing) {
  70013. this.imageProcessing.shareOutputWith(this.pass);
  70014. this.imageProcessing.autoClear = false;
  70015. }
  70016. else {
  70017. this.finalMerge.shareOutputWith(this.pass);
  70018. }
  70019. }
  70020. else {
  70021. this.finalMerge.shareOutputWith(this.pass);
  70022. }
  70023. }
  70024. if (this.fxaaEnabled) {
  70025. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70026. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  70027. this._setAutoClearAndTextureSharing(this.fxaa);
  70028. }
  70029. if (this.chromaticAberrationEnabled) {
  70030. if (!this.chromaticAberration.isReady()) {
  70031. this.chromaticAberration.updateEffect();
  70032. }
  70033. this.addEffect(this._chromaticAberrationEffect);
  70034. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  70035. }
  70036. if (this._cameras !== null) {
  70037. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  70038. }
  70039. if (this.msaaEnabled) {
  70040. if (!this._enableMSAAOnFirstPostProcess()) {
  70041. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  70042. }
  70043. }
  70044. };
  70045. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  70046. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  70047. for (var i = 0; i < this._cameras.length; i++) {
  70048. var camera = this._cameras[i];
  70049. if (this.pass) {
  70050. this.pass.dispose(camera);
  70051. }
  70052. if (this.highlights) {
  70053. this.highlights.dispose(camera);
  70054. }
  70055. if (this.blurX) {
  70056. this.blurX.dispose(camera);
  70057. }
  70058. if (this.blurY) {
  70059. this.blurY.dispose(camera);
  70060. }
  70061. if (this.copyBack) {
  70062. this.copyBack.dispose(camera);
  70063. }
  70064. if (this.imageProcessing) {
  70065. this.imageProcessing.dispose(camera);
  70066. }
  70067. if (this.fxaa) {
  70068. this.fxaa.dispose(camera);
  70069. }
  70070. if (this.finalMerge) {
  70071. this.finalMerge.dispose(camera);
  70072. }
  70073. // These are created in the constructor and should not be disposed on every pipeline change
  70074. if (disposeNonRecreated) {
  70075. if (this.sharpen) {
  70076. this.sharpen.dispose(camera);
  70077. }
  70078. if (this.depthOfField) {
  70079. this.depthOfField.disposeEffects(camera);
  70080. }
  70081. if (this.chromaticAberration) {
  70082. this.chromaticAberration.dispose(camera);
  70083. }
  70084. }
  70085. }
  70086. this.pass = null;
  70087. this.highlights = null;
  70088. this.blurX = null;
  70089. this.blurY = null;
  70090. this.copyBack = null;
  70091. this.imageProcessing = null;
  70092. this.fxaa = null;
  70093. this.finalMerge = null;
  70094. if (disposeNonRecreated) {
  70095. this.sharpen = null;
  70096. this.depthOfField = null;
  70097. this.chromaticAberration = null;
  70098. }
  70099. };
  70100. /**
  70101. * Dispose of the pipeline and stop all post processes
  70102. */
  70103. DefaultRenderingPipeline.prototype.dispose = function () {
  70104. this._disposePostProcesses(true);
  70105. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  70106. _super.prototype.dispose.call(this);
  70107. };
  70108. /**
  70109. * Serialize the rendering pipeline (Used when exporting)
  70110. * @returns the serialized object
  70111. */
  70112. DefaultRenderingPipeline.prototype.serialize = function () {
  70113. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  70114. serializationObject.customType = "DefaultRenderingPipeline";
  70115. return serializationObject;
  70116. };
  70117. /**
  70118. * Parse the serialized pipeline
  70119. * @param source Source pipeline.
  70120. * @param scene The scene to load the pipeline to.
  70121. * @param rootUrl The URL of the serialized pipeline.
  70122. * @returns An instantiated pipeline from the serialized object.
  70123. */
  70124. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  70125. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  70126. };
  70127. __decorate([
  70128. BABYLON.serialize()
  70129. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  70130. __decorate([
  70131. BABYLON.serialize()
  70132. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  70133. __decorate([
  70134. BABYLON.serialize()
  70135. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  70136. __decorate([
  70137. BABYLON.serialize()
  70138. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  70139. __decorate([
  70140. BABYLON.serialize()
  70141. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  70142. __decorate([
  70143. BABYLON.serialize()
  70144. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  70145. __decorate([
  70146. BABYLON.serialize()
  70147. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  70148. __decorate([
  70149. BABYLON.serialize()
  70150. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  70151. __decorate([
  70152. BABYLON.serialize()
  70153. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  70154. __decorate([
  70155. BABYLON.serialize()
  70156. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  70157. __decorate([
  70158. BABYLON.serialize()
  70159. ], DefaultRenderingPipeline.prototype, "msaaEnabled", null);
  70160. __decorate([
  70161. BABYLON.serialize()
  70162. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  70163. __decorate([
  70164. BABYLON.serialize()
  70165. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  70166. return DefaultRenderingPipeline;
  70167. }(BABYLON.PostProcessRenderPipeline));
  70168. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  70169. })(BABYLON || (BABYLON = {}));
  70170. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  70171. "use strict";
  70172. var BABYLON;
  70173. (function (BABYLON) {
  70174. /**
  70175. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  70176. */
  70177. var GeometryBufferRenderer = /** @class */ (function () {
  70178. /**
  70179. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  70180. * @param scene The scene the buffer belongs to
  70181. * @param ratio How big is the buffer related to the main canvas.
  70182. */
  70183. function GeometryBufferRenderer(scene, ratio) {
  70184. if (ratio === void 0) { ratio = 1; }
  70185. this._enablePosition = false;
  70186. this._scene = scene;
  70187. this._ratio = ratio;
  70188. // Render target
  70189. this._createRenderTargets();
  70190. }
  70191. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  70192. /**
  70193. * Set the render list (meshes to be rendered) used in the G buffer.
  70194. */
  70195. set: function (meshes) {
  70196. this._multiRenderTarget.renderList = meshes;
  70197. },
  70198. enumerable: true,
  70199. configurable: true
  70200. });
  70201. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  70202. /**
  70203. * Gets wether or not G buffer are supported by the running hardware.
  70204. * This requires draw buffer supports
  70205. */
  70206. get: function () {
  70207. return this._multiRenderTarget.isSupported;
  70208. },
  70209. enumerable: true,
  70210. configurable: true
  70211. });
  70212. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  70213. /**
  70214. * Gets wether or not position are enabled for the G buffer.
  70215. */
  70216. get: function () {
  70217. return this._enablePosition;
  70218. },
  70219. /**
  70220. * Sets wether or not position are enabled for the G buffer.
  70221. */
  70222. set: function (enable) {
  70223. this._enablePosition = enable;
  70224. this.dispose();
  70225. this._createRenderTargets();
  70226. },
  70227. enumerable: true,
  70228. configurable: true
  70229. });
  70230. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  70231. /**
  70232. * Gets the scene associated with the buffer.
  70233. */
  70234. get: function () {
  70235. return this._scene;
  70236. },
  70237. enumerable: true,
  70238. configurable: true
  70239. });
  70240. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  70241. /**
  70242. * Gets the ratio used by the buffer during its creation.
  70243. * How big is the buffer related to the main canvas.
  70244. */
  70245. get: function () {
  70246. return this._ratio;
  70247. },
  70248. enumerable: true,
  70249. configurable: true
  70250. });
  70251. /**
  70252. * Checks wether everything is ready to render a submesh to the G buffer.
  70253. * @param subMesh the submesh to check readiness for
  70254. * @param useInstances is the mesh drawn using instance or not
  70255. * @returns true if ready otherwise false
  70256. */
  70257. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  70258. var material = subMesh.getMaterial();
  70259. if (material && material.disableDepthWrite) {
  70260. return false;
  70261. }
  70262. var defines = [];
  70263. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  70264. var mesh = subMesh.getMesh();
  70265. // Alpha test
  70266. if (material && material.needAlphaTesting()) {
  70267. defines.push("#define ALPHATEST");
  70268. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70269. attribs.push(BABYLON.VertexBuffer.UVKind);
  70270. defines.push("#define UV1");
  70271. }
  70272. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70273. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70274. defines.push("#define UV2");
  70275. }
  70276. }
  70277. // Buffers
  70278. if (this._enablePosition) {
  70279. defines.push("#define POSITION");
  70280. }
  70281. // Bones
  70282. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70283. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70284. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70285. if (mesh.numBoneInfluencers > 4) {
  70286. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  70287. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  70288. }
  70289. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70290. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  70291. }
  70292. else {
  70293. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70294. }
  70295. // Instances
  70296. if (useInstances) {
  70297. defines.push("#define INSTANCES");
  70298. attribs.push("world0");
  70299. attribs.push("world1");
  70300. attribs.push("world2");
  70301. attribs.push("world3");
  70302. }
  70303. // Get correct effect
  70304. var join = defines.join("\n");
  70305. if (this._cachedDefines !== join) {
  70306. this._cachedDefines = join;
  70307. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  70308. }
  70309. return this._effect.isReady();
  70310. };
  70311. /**
  70312. * Gets the current underlying G Buffer.
  70313. * @returns the buffer
  70314. */
  70315. GeometryBufferRenderer.prototype.getGBuffer = function () {
  70316. return this._multiRenderTarget;
  70317. };
  70318. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  70319. /**
  70320. * Gets the number of samples used to render the buffer (anti aliasing).
  70321. */
  70322. get: function () {
  70323. return this._multiRenderTarget.samples;
  70324. },
  70325. /**
  70326. * Sets the number of samples used to render the buffer (anti aliasing).
  70327. */
  70328. set: function (value) {
  70329. this._multiRenderTarget.samples = value;
  70330. },
  70331. enumerable: true,
  70332. configurable: true
  70333. });
  70334. /**
  70335. * Disposes the renderer and frees up associated resources.
  70336. */
  70337. GeometryBufferRenderer.prototype.dispose = function () {
  70338. this.getGBuffer().dispose();
  70339. };
  70340. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  70341. var _this = this;
  70342. var engine = this._scene.getEngine();
  70343. var count = this._enablePosition ? 3 : 2;
  70344. 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 });
  70345. if (!this.isSupported) {
  70346. return;
  70347. }
  70348. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70349. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70350. this._multiRenderTarget.refreshRate = 1;
  70351. this._multiRenderTarget.renderParticles = false;
  70352. this._multiRenderTarget.renderList = null;
  70353. // set default depth value to 1.0 (far away)
  70354. this._multiRenderTarget.onClearObservable.add(function (engine) {
  70355. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  70356. });
  70357. // Custom render function
  70358. var renderSubMesh = function (subMesh) {
  70359. var mesh = subMesh.getRenderingMesh();
  70360. var scene = _this._scene;
  70361. var engine = scene.getEngine();
  70362. var material = subMesh.getMaterial();
  70363. if (!material) {
  70364. return;
  70365. }
  70366. // Culling
  70367. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  70368. // Managing instances
  70369. var batch = mesh._getInstancesRenderList(subMesh._id);
  70370. if (batch.mustReturn) {
  70371. return;
  70372. }
  70373. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  70374. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  70375. engine.enableEffect(_this._effect);
  70376. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  70377. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  70378. _this._effect.setMatrix("view", scene.getViewMatrix());
  70379. // Alpha test
  70380. if (material && material.needAlphaTesting()) {
  70381. var alphaTexture = material.getAlphaTestTexture();
  70382. if (alphaTexture) {
  70383. _this._effect.setTexture("diffuseSampler", alphaTexture);
  70384. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  70385. }
  70386. }
  70387. // Bones
  70388. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  70389. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  70390. }
  70391. // Draw
  70392. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  70393. }
  70394. };
  70395. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  70396. var index;
  70397. if (depthOnlySubMeshes.length) {
  70398. engine.setColorWrite(false);
  70399. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70400. renderSubMesh(depthOnlySubMeshes.data[index]);
  70401. }
  70402. engine.setColorWrite(true);
  70403. }
  70404. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70405. renderSubMesh(opaqueSubMeshes.data[index]);
  70406. }
  70407. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70408. renderSubMesh(alphaTestSubMeshes.data[index]);
  70409. }
  70410. };
  70411. };
  70412. return GeometryBufferRenderer;
  70413. }());
  70414. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  70415. })(BABYLON || (BABYLON = {}));
  70416. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  70417. "use strict";
  70418. var BABYLON;
  70419. (function (BABYLON) {
  70420. var RefractionPostProcess = /** @class */ (function (_super) {
  70421. __extends(RefractionPostProcess, _super);
  70422. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  70423. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  70424. _this.color = color;
  70425. _this.depth = depth;
  70426. _this.colorLevel = colorLevel;
  70427. _this._ownRefractionTexture = true;
  70428. _this.onActivateObservable.add(function (cam) {
  70429. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  70430. });
  70431. _this.onApplyObservable.add(function (effect) {
  70432. effect.setColor3("baseColor", _this.color);
  70433. effect.setFloat("depth", _this.depth);
  70434. effect.setFloat("colorLevel", _this.colorLevel);
  70435. effect.setTexture("refractionSampler", _this._refTexture);
  70436. });
  70437. return _this;
  70438. }
  70439. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  70440. /**
  70441. * Gets or sets the refraction texture
  70442. * Please note that you are responsible for disposing the texture if you set it manually
  70443. */
  70444. get: function () {
  70445. return this._refTexture;
  70446. },
  70447. set: function (value) {
  70448. if (this._refTexture && this._ownRefractionTexture) {
  70449. this._refTexture.dispose();
  70450. }
  70451. this._refTexture = value;
  70452. this._ownRefractionTexture = false;
  70453. },
  70454. enumerable: true,
  70455. configurable: true
  70456. });
  70457. // Methods
  70458. RefractionPostProcess.prototype.dispose = function (camera) {
  70459. if (this._refTexture && this._ownRefractionTexture) {
  70460. this._refTexture.dispose();
  70461. this._refTexture = null;
  70462. }
  70463. _super.prototype.dispose.call(this, camera);
  70464. };
  70465. return RefractionPostProcess;
  70466. }(BABYLON.PostProcess));
  70467. BABYLON.RefractionPostProcess = RefractionPostProcess;
  70468. })(BABYLON || (BABYLON = {}));
  70469. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  70470. "use strict";
  70471. var BABYLON;
  70472. (function (BABYLON) {
  70473. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  70474. __extends(BlackAndWhitePostProcess, _super);
  70475. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  70476. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  70477. _this.degree = 1;
  70478. _this.onApplyObservable.add(function (effect) {
  70479. effect.setFloat("degree", _this.degree);
  70480. });
  70481. return _this;
  70482. }
  70483. return BlackAndWhitePostProcess;
  70484. }(BABYLON.PostProcess));
  70485. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  70486. })(BABYLON || (BABYLON = {}));
  70487. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  70488. "use strict";
  70489. var BABYLON;
  70490. (function (BABYLON) {
  70491. /**
  70492. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  70493. * input texture to perform effects such as edge detection or sharpening
  70494. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  70495. */
  70496. var ConvolutionPostProcess = /** @class */ (function (_super) {
  70497. __extends(ConvolutionPostProcess, _super);
  70498. /**
  70499. * Creates a new instance of @see ConvolutionPostProcess
  70500. * @param name The name of the effect.
  70501. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  70502. * @param options The required width/height ratio to downsize to before computing the render pass.
  70503. * @param camera The camera to apply the render pass to.
  70504. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70505. * @param engine The engine which the post process will be applied. (default: current engine)
  70506. * @param reusable If the post process can be reused on the same frame. (default: false)
  70507. * @param textureType Type of textures used when performing the post process. (default: 0)
  70508. */
  70509. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  70510. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70511. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  70512. _this.kernel = kernel;
  70513. _this.onApply = function (effect) {
  70514. effect.setFloat2("screenSize", _this.width, _this.height);
  70515. effect.setArray("kernel", _this.kernel);
  70516. };
  70517. return _this;
  70518. }
  70519. // Statics
  70520. /**
  70521. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70522. */
  70523. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  70524. /**
  70525. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70526. */
  70527. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  70528. /**
  70529. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70530. */
  70531. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  70532. /**
  70533. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70534. */
  70535. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  70536. /**
  70537. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70538. */
  70539. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  70540. /**
  70541. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70542. */
  70543. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  70544. return ConvolutionPostProcess;
  70545. }(BABYLON.PostProcess));
  70546. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  70547. })(BABYLON || (BABYLON = {}));
  70548. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  70549. "use strict";
  70550. var BABYLON;
  70551. (function (BABYLON) {
  70552. var FilterPostProcess = /** @class */ (function (_super) {
  70553. __extends(FilterPostProcess, _super);
  70554. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  70555. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  70556. _this.kernelMatrix = kernelMatrix;
  70557. _this.onApply = function (effect) {
  70558. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  70559. };
  70560. return _this;
  70561. }
  70562. return FilterPostProcess;
  70563. }(BABYLON.PostProcess));
  70564. BABYLON.FilterPostProcess = FilterPostProcess;
  70565. })(BABYLON || (BABYLON = {}));
  70566. //# sourceMappingURL=babylon.filterPostProcess.js.map
  70567. "use strict";
  70568. var BABYLON;
  70569. (function (BABYLON) {
  70570. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  70571. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  70572. __extends(VolumetricLightScatteringPostProcess, _super);
  70573. /**
  70574. * @constructor
  70575. * @param {string} name - The post-process name
  70576. * @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)
  70577. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  70578. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  70579. * @param {number} samples - The post-process quality, default 100
  70580. * @param {number} samplingMode - The post-process filtering mode
  70581. * @param {BABYLON.Engine} engine - The babylon engine
  70582. * @param {boolean} reusable - If the post-process is reusable
  70583. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  70584. */
  70585. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  70586. if (samples === void 0) { samples = 100; }
  70587. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70588. 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;
  70589. _this._screenCoordinates = BABYLON.Vector2.Zero();
  70590. /**
  70591. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  70592. * @type {Vector3}
  70593. */
  70594. _this.customMeshPosition = BABYLON.Vector3.Zero();
  70595. /**
  70596. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  70597. * @type {boolean}
  70598. */
  70599. _this.useCustomMeshPosition = false;
  70600. /**
  70601. * If the post-process should inverse the light scattering direction
  70602. * @type {boolean}
  70603. */
  70604. _this.invert = true;
  70605. /**
  70606. * Array containing the excluded meshes not rendered in the internal pass
  70607. */
  70608. _this.excludedMeshes = new Array();
  70609. /**
  70610. * Controls the overall intensity of the post-process
  70611. * @type {number}
  70612. */
  70613. _this.exposure = 0.3;
  70614. /**
  70615. * Dissipates each sample's contribution in range [0, 1]
  70616. * @type {number}
  70617. */
  70618. _this.decay = 0.96815;
  70619. /**
  70620. * Controls the overall intensity of each sample
  70621. * @type {number}
  70622. */
  70623. _this.weight = 0.58767;
  70624. /**
  70625. * Controls the density of each sample
  70626. * @type {number}
  70627. */
  70628. _this.density = 0.926;
  70629. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  70630. engine = scene.getEngine();
  70631. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  70632. // Configure mesh
  70633. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  70634. // Configure
  70635. _this._createPass(scene, ratio.passRatio || ratio);
  70636. _this.onActivate = function (camera) {
  70637. if (!_this.isSupported) {
  70638. _this.dispose(camera);
  70639. }
  70640. _this.onActivate = null;
  70641. };
  70642. _this.onApplyObservable.add(function (effect) {
  70643. _this._updateMeshScreenCoordinates(scene);
  70644. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  70645. effect.setFloat("exposure", _this.exposure);
  70646. effect.setFloat("decay", _this.decay);
  70647. effect.setFloat("weight", _this.weight);
  70648. effect.setFloat("density", _this.density);
  70649. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  70650. });
  70651. return _this;
  70652. }
  70653. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  70654. get: function () {
  70655. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  70656. return false;
  70657. },
  70658. set: function (useDiffuseColor) {
  70659. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  70660. },
  70661. enumerable: true,
  70662. configurable: true
  70663. });
  70664. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  70665. return "VolumetricLightScatteringPostProcess";
  70666. };
  70667. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  70668. var mesh = subMesh.getMesh();
  70669. // Render this.mesh as default
  70670. if (mesh === this.mesh && mesh.material) {
  70671. return mesh.material.isReady(mesh);
  70672. }
  70673. var defines = [];
  70674. var attribs = [BABYLON.VertexBuffer.PositionKind];
  70675. var material = subMesh.getMaterial();
  70676. // Alpha test
  70677. if (material) {
  70678. if (material.needAlphaTesting()) {
  70679. defines.push("#define ALPHATEST");
  70680. }
  70681. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70682. attribs.push(BABYLON.VertexBuffer.UVKind);
  70683. defines.push("#define UV1");
  70684. }
  70685. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70686. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70687. defines.push("#define UV2");
  70688. }
  70689. }
  70690. // Bones
  70691. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70692. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70693. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70694. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70695. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  70696. }
  70697. else {
  70698. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70699. }
  70700. // Instances
  70701. if (useInstances) {
  70702. defines.push("#define INSTANCES");
  70703. attribs.push("world0");
  70704. attribs.push("world1");
  70705. attribs.push("world2");
  70706. attribs.push("world3");
  70707. }
  70708. // Get correct effect
  70709. var join = defines.join("\n");
  70710. if (this._cachedDefines !== join) {
  70711. this._cachedDefines = join;
  70712. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  70713. }
  70714. return this._volumetricLightScatteringPass.isReady();
  70715. };
  70716. /**
  70717. * Sets the new light position for light scattering effect
  70718. * @param {BABYLON.Vector3} The new custom light position
  70719. */
  70720. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  70721. this.customMeshPosition = position;
  70722. };
  70723. /**
  70724. * Returns the light position for light scattering effect
  70725. * @return {BABYLON.Vector3} The custom light position
  70726. */
  70727. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  70728. return this.customMeshPosition;
  70729. };
  70730. /**
  70731. * Disposes the internal assets and detaches the post-process from the camera
  70732. */
  70733. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  70734. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  70735. if (rttIndex !== -1) {
  70736. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  70737. }
  70738. this._volumetricLightScatteringRTT.dispose();
  70739. _super.prototype.dispose.call(this, camera);
  70740. };
  70741. /**
  70742. * Returns the render target texture used by the post-process
  70743. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  70744. */
  70745. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  70746. return this._volumetricLightScatteringRTT;
  70747. };
  70748. // Private methods
  70749. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  70750. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  70751. return true;
  70752. }
  70753. return false;
  70754. };
  70755. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  70756. var _this = this;
  70757. var engine = scene.getEngine();
  70758. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  70759. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70760. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70761. this._volumetricLightScatteringRTT.renderList = null;
  70762. this._volumetricLightScatteringRTT.renderParticles = false;
  70763. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  70764. var camera = this.getCamera();
  70765. if (camera) {
  70766. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  70767. }
  70768. else {
  70769. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  70770. }
  70771. // Custom render function for submeshes
  70772. var renderSubMesh = function (subMesh) {
  70773. var mesh = subMesh.getRenderingMesh();
  70774. if (_this._meshExcluded(mesh)) {
  70775. return;
  70776. }
  70777. var material = subMesh.getMaterial();
  70778. if (!material) {
  70779. return;
  70780. }
  70781. var scene = mesh.getScene();
  70782. var engine = scene.getEngine();
  70783. // Culling
  70784. engine.setState(material.backFaceCulling);
  70785. // Managing instances
  70786. var batch = mesh._getInstancesRenderList(subMesh._id);
  70787. if (batch.mustReturn) {
  70788. return;
  70789. }
  70790. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  70791. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  70792. var effect = _this._volumetricLightScatteringPass;
  70793. if (mesh === _this.mesh) {
  70794. if (subMesh.effect) {
  70795. effect = subMesh.effect;
  70796. }
  70797. else {
  70798. effect = material.getEffect();
  70799. }
  70800. }
  70801. engine.enableEffect(effect);
  70802. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  70803. if (mesh === _this.mesh) {
  70804. material.bind(mesh.getWorldMatrix(), mesh);
  70805. }
  70806. else {
  70807. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  70808. // Alpha test
  70809. if (material && material.needAlphaTesting()) {
  70810. var alphaTexture = material.getAlphaTestTexture();
  70811. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  70812. if (alphaTexture) {
  70813. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  70814. }
  70815. }
  70816. // Bones
  70817. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  70818. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  70819. }
  70820. }
  70821. // Draw
  70822. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  70823. }
  70824. };
  70825. // Render target texture callbacks
  70826. var savedSceneClearColor;
  70827. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  70828. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  70829. savedSceneClearColor = scene.clearColor;
  70830. scene.clearColor = sceneClearColor;
  70831. });
  70832. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  70833. scene.clearColor = savedSceneClearColor;
  70834. });
  70835. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  70836. var engine = scene.getEngine();
  70837. var index;
  70838. if (depthOnlySubMeshes.length) {
  70839. engine.setColorWrite(false);
  70840. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70841. renderSubMesh(depthOnlySubMeshes.data[index]);
  70842. }
  70843. engine.setColorWrite(true);
  70844. }
  70845. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70846. renderSubMesh(opaqueSubMeshes.data[index]);
  70847. }
  70848. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70849. renderSubMesh(alphaTestSubMeshes.data[index]);
  70850. }
  70851. if (transparentSubMeshes.length) {
  70852. // Sort sub meshes
  70853. for (index = 0; index < transparentSubMeshes.length; index++) {
  70854. var submesh = transparentSubMeshes.data[index];
  70855. var boundingInfo = submesh.getBoundingInfo();
  70856. if (boundingInfo && scene.activeCamera) {
  70857. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  70858. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  70859. }
  70860. }
  70861. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  70862. sortedArray.sort(function (a, b) {
  70863. // Alpha index first
  70864. if (a._alphaIndex > b._alphaIndex) {
  70865. return 1;
  70866. }
  70867. if (a._alphaIndex < b._alphaIndex) {
  70868. return -1;
  70869. }
  70870. // Then distance to camera
  70871. if (a._distanceToCamera < b._distanceToCamera) {
  70872. return 1;
  70873. }
  70874. if (a._distanceToCamera > b._distanceToCamera) {
  70875. return -1;
  70876. }
  70877. return 0;
  70878. });
  70879. // Render sub meshes
  70880. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  70881. for (index = 0; index < sortedArray.length; index++) {
  70882. renderSubMesh(sortedArray[index]);
  70883. }
  70884. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  70885. }
  70886. };
  70887. };
  70888. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  70889. var transform = scene.getTransformMatrix();
  70890. var meshPosition;
  70891. if (this.useCustomMeshPosition) {
  70892. meshPosition = this.customMeshPosition;
  70893. }
  70894. else if (this.attachedNode) {
  70895. meshPosition = this.attachedNode.position;
  70896. }
  70897. else {
  70898. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  70899. }
  70900. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  70901. this._screenCoordinates.x = pos.x / this._viewPort.width;
  70902. this._screenCoordinates.y = pos.y / this._viewPort.height;
  70903. if (this.invert)
  70904. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  70905. };
  70906. // Static methods
  70907. /**
  70908. * Creates a default mesh for the Volumeric Light Scattering post-process
  70909. * @param {string} The mesh name
  70910. * @param {BABYLON.Scene} The scene where to create the mesh
  70911. * @return {BABYLON.Mesh} the default mesh
  70912. */
  70913. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  70914. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  70915. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  70916. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  70917. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  70918. mesh.material = material;
  70919. return mesh;
  70920. };
  70921. __decorate([
  70922. BABYLON.serializeAsVector3()
  70923. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  70924. __decorate([
  70925. BABYLON.serialize()
  70926. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  70927. __decorate([
  70928. BABYLON.serialize()
  70929. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  70930. __decorate([
  70931. BABYLON.serializeAsMeshReference()
  70932. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  70933. __decorate([
  70934. BABYLON.serialize()
  70935. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  70936. __decorate([
  70937. BABYLON.serialize()
  70938. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  70939. __decorate([
  70940. BABYLON.serialize()
  70941. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  70942. __decorate([
  70943. BABYLON.serialize()
  70944. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  70945. __decorate([
  70946. BABYLON.serialize()
  70947. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  70948. return VolumetricLightScatteringPostProcess;
  70949. }(BABYLON.PostProcess));
  70950. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  70951. })(BABYLON || (BABYLON = {}));
  70952. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  70953. "use strict";
  70954. //
  70955. // This post-process allows the modification of rendered colors by using
  70956. // a 'look-up table' (LUT). This effect is also called Color Grading.
  70957. //
  70958. // The object needs to be provided an url to a texture containing the color
  70959. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  70960. // Use an image editing software to tweak the LUT to match your needs.
  70961. //
  70962. // For an example of a color LUT, see here:
  70963. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  70964. // For explanations on color grading, see here:
  70965. // http://udn.epicgames.com/Three/ColorGrading.html
  70966. //
  70967. var BABYLON;
  70968. (function (BABYLON) {
  70969. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  70970. __extends(ColorCorrectionPostProcess, _super);
  70971. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  70972. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  70973. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  70974. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  70975. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70976. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70977. _this.onApply = function (effect) {
  70978. effect.setTexture("colorTable", _this._colorTableTexture);
  70979. };
  70980. return _this;
  70981. }
  70982. return ColorCorrectionPostProcess;
  70983. }(BABYLON.PostProcess));
  70984. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  70985. })(BABYLON || (BABYLON = {}));
  70986. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  70987. "use strict";
  70988. var BABYLON;
  70989. (function (BABYLON) {
  70990. var TonemappingOperator;
  70991. (function (TonemappingOperator) {
  70992. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  70993. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  70994. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  70995. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  70996. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  70997. ;
  70998. var TonemapPostProcess = /** @class */ (function (_super) {
  70999. __extends(TonemapPostProcess, _super);
  71000. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  71001. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71002. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71003. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  71004. _this._operator = _operator;
  71005. _this.exposureAdjustment = exposureAdjustment;
  71006. var defines = "#define ";
  71007. if (_this._operator === TonemappingOperator.Hable)
  71008. defines += "HABLE_TONEMAPPING";
  71009. else if (_this._operator === TonemappingOperator.Reinhard)
  71010. defines += "REINHARD_TONEMAPPING";
  71011. else if (_this._operator === TonemappingOperator.HejiDawson)
  71012. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  71013. else if (_this._operator === TonemappingOperator.Photographic)
  71014. defines += "PHOTOGRAPHIC_TONEMAPPING";
  71015. //sadly a second call to create the effect.
  71016. _this.updateEffect(defines);
  71017. _this.onApply = function (effect) {
  71018. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  71019. };
  71020. return _this;
  71021. }
  71022. return TonemapPostProcess;
  71023. }(BABYLON.PostProcess));
  71024. BABYLON.TonemapPostProcess = TonemapPostProcess;
  71025. })(BABYLON || (BABYLON = {}));
  71026. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  71027. "use strict";
  71028. var BABYLON;
  71029. (function (BABYLON) {
  71030. var DisplayPassPostProcess = /** @class */ (function (_super) {
  71031. __extends(DisplayPassPostProcess, _super);
  71032. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  71033. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  71034. }
  71035. return DisplayPassPostProcess;
  71036. }(BABYLON.PostProcess));
  71037. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  71038. })(BABYLON || (BABYLON = {}));
  71039. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  71040. "use strict";
  71041. var BABYLON;
  71042. (function (BABYLON) {
  71043. var HighlightsPostProcess = /** @class */ (function (_super) {
  71044. __extends(HighlightsPostProcess, _super);
  71045. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  71046. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71047. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  71048. }
  71049. return HighlightsPostProcess;
  71050. }(BABYLON.PostProcess));
  71051. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  71052. })(BABYLON || (BABYLON = {}));
  71053. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  71054. "use strict";
  71055. var BABYLON;
  71056. (function (BABYLON) {
  71057. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  71058. __extends(ImageProcessingPostProcess, _super);
  71059. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  71060. if (camera === void 0) { camera = null; }
  71061. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71062. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  71063. _this._fromLinearSpace = true;
  71064. /**
  71065. * Defines cache preventing GC.
  71066. */
  71067. _this._defines = {
  71068. IMAGEPROCESSING: false,
  71069. VIGNETTE: false,
  71070. VIGNETTEBLENDMODEMULTIPLY: false,
  71071. VIGNETTEBLENDMODEOPAQUE: false,
  71072. TONEMAPPING: false,
  71073. CONTRAST: false,
  71074. COLORCURVES: false,
  71075. COLORGRADING: false,
  71076. COLORGRADING3D: false,
  71077. FROMLINEARSPACE: false,
  71078. SAMPLER3DGREENDEPTH: false,
  71079. SAMPLER3DBGRMAP: false,
  71080. IMAGEPROCESSINGPOSTPROCESS: false,
  71081. EXPOSURE: false,
  71082. GRAIN: false,
  71083. };
  71084. // Setup the configuration as forced by the constructor. This would then not force the
  71085. // scene materials output in linear space and let untouched the default forward pass.
  71086. if (imageProcessingConfiguration) {
  71087. imageProcessingConfiguration.applyByPostProcess = true;
  71088. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  71089. // This will cause the shader to be compiled
  71090. _this.fromLinearSpace = false;
  71091. }
  71092. else {
  71093. _this._attachImageProcessingConfiguration(null, true);
  71094. _this.imageProcessingConfiguration.applyByPostProcess = true;
  71095. }
  71096. _this.onApply = function (effect) {
  71097. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  71098. };
  71099. return _this;
  71100. }
  71101. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  71102. /**
  71103. * Gets the image processing configuration used either in this material.
  71104. */
  71105. get: function () {
  71106. return this._imageProcessingConfiguration;
  71107. },
  71108. /**
  71109. * Sets the Default image processing configuration used either in the this material.
  71110. *
  71111. * If sets to null, the scene one is in use.
  71112. */
  71113. set: function (value) {
  71114. this._attachImageProcessingConfiguration(value);
  71115. },
  71116. enumerable: true,
  71117. configurable: true
  71118. });
  71119. /**
  71120. * Attaches a new image processing configuration to the PBR Material.
  71121. * @param configuration
  71122. */
  71123. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  71124. var _this = this;
  71125. if (doNotBuild === void 0) { doNotBuild = false; }
  71126. if (configuration === this._imageProcessingConfiguration) {
  71127. return;
  71128. }
  71129. // Detaches observer.
  71130. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  71131. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  71132. }
  71133. // Pick the scene configuration if needed.
  71134. if (!configuration) {
  71135. var scene = null;
  71136. var engine = this.getEngine();
  71137. var camera = this.getCamera();
  71138. if (camera) {
  71139. scene = camera.getScene();
  71140. }
  71141. else if (engine && engine.scenes) {
  71142. var scenes = engine.scenes;
  71143. scene = scenes[scenes.length - 1];
  71144. }
  71145. else {
  71146. scene = BABYLON.Engine.LastCreatedScene;
  71147. }
  71148. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  71149. }
  71150. else {
  71151. this._imageProcessingConfiguration = configuration;
  71152. }
  71153. // Attaches observer.
  71154. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  71155. _this._updateParameters();
  71156. });
  71157. // Ensure the effect will be rebuilt.
  71158. if (!doNotBuild) {
  71159. this._updateParameters();
  71160. }
  71161. };
  71162. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  71163. /**
  71164. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  71165. */
  71166. get: function () {
  71167. return this.imageProcessingConfiguration.colorCurves;
  71168. },
  71169. /**
  71170. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  71171. */
  71172. set: function (value) {
  71173. this.imageProcessingConfiguration.colorCurves = value;
  71174. },
  71175. enumerable: true,
  71176. configurable: true
  71177. });
  71178. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  71179. /**
  71180. * Gets wether the color curves effect is enabled.
  71181. */
  71182. get: function () {
  71183. return this.imageProcessingConfiguration.colorCurvesEnabled;
  71184. },
  71185. /**
  71186. * Sets wether the color curves effect is enabled.
  71187. */
  71188. set: function (value) {
  71189. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  71190. },
  71191. enumerable: true,
  71192. configurable: true
  71193. });
  71194. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  71195. /**
  71196. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  71197. */
  71198. get: function () {
  71199. return this.imageProcessingConfiguration.colorGradingTexture;
  71200. },
  71201. /**
  71202. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  71203. */
  71204. set: function (value) {
  71205. this.imageProcessingConfiguration.colorGradingTexture = value;
  71206. },
  71207. enumerable: true,
  71208. configurable: true
  71209. });
  71210. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  71211. /**
  71212. * Gets wether the color grading effect is enabled.
  71213. */
  71214. get: function () {
  71215. return this.imageProcessingConfiguration.colorGradingEnabled;
  71216. },
  71217. /**
  71218. * Gets wether the color grading effect is enabled.
  71219. */
  71220. set: function (value) {
  71221. this.imageProcessingConfiguration.colorGradingEnabled = value;
  71222. },
  71223. enumerable: true,
  71224. configurable: true
  71225. });
  71226. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  71227. /**
  71228. * Gets exposure used in the effect.
  71229. */
  71230. get: function () {
  71231. return this.imageProcessingConfiguration.exposure;
  71232. },
  71233. /**
  71234. * Sets exposure used in the effect.
  71235. */
  71236. set: function (value) {
  71237. this.imageProcessingConfiguration.exposure = value;
  71238. },
  71239. enumerable: true,
  71240. configurable: true
  71241. });
  71242. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  71243. /**
  71244. * Gets wether tonemapping is enabled or not.
  71245. */
  71246. get: function () {
  71247. return this._imageProcessingConfiguration.toneMappingEnabled;
  71248. },
  71249. /**
  71250. * Sets wether tonemapping is enabled or not
  71251. */
  71252. set: function (value) {
  71253. this._imageProcessingConfiguration.toneMappingEnabled = value;
  71254. },
  71255. enumerable: true,
  71256. configurable: true
  71257. });
  71258. ;
  71259. ;
  71260. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  71261. /**
  71262. * Gets contrast used in the effect.
  71263. */
  71264. get: function () {
  71265. return this.imageProcessingConfiguration.contrast;
  71266. },
  71267. /**
  71268. * Sets contrast used in the effect.
  71269. */
  71270. set: function (value) {
  71271. this.imageProcessingConfiguration.contrast = value;
  71272. },
  71273. enumerable: true,
  71274. configurable: true
  71275. });
  71276. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  71277. /**
  71278. * Gets Vignette stretch size.
  71279. */
  71280. get: function () {
  71281. return this.imageProcessingConfiguration.vignetteStretch;
  71282. },
  71283. /**
  71284. * Sets Vignette stretch size.
  71285. */
  71286. set: function (value) {
  71287. this.imageProcessingConfiguration.vignetteStretch = value;
  71288. },
  71289. enumerable: true,
  71290. configurable: true
  71291. });
  71292. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  71293. /**
  71294. * Gets Vignette centre X Offset.
  71295. */
  71296. get: function () {
  71297. return this.imageProcessingConfiguration.vignetteCentreX;
  71298. },
  71299. /**
  71300. * Sets Vignette centre X Offset.
  71301. */
  71302. set: function (value) {
  71303. this.imageProcessingConfiguration.vignetteCentreX = value;
  71304. },
  71305. enumerable: true,
  71306. configurable: true
  71307. });
  71308. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  71309. /**
  71310. * Gets Vignette centre Y Offset.
  71311. */
  71312. get: function () {
  71313. return this.imageProcessingConfiguration.vignetteCentreY;
  71314. },
  71315. /**
  71316. * Sets Vignette centre Y Offset.
  71317. */
  71318. set: function (value) {
  71319. this.imageProcessingConfiguration.vignetteCentreY = value;
  71320. },
  71321. enumerable: true,
  71322. configurable: true
  71323. });
  71324. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  71325. /**
  71326. * Gets Vignette weight or intensity of the vignette effect.
  71327. */
  71328. get: function () {
  71329. return this.imageProcessingConfiguration.vignetteWeight;
  71330. },
  71331. /**
  71332. * Sets Vignette weight or intensity of the vignette effect.
  71333. */
  71334. set: function (value) {
  71335. this.imageProcessingConfiguration.vignetteWeight = value;
  71336. },
  71337. enumerable: true,
  71338. configurable: true
  71339. });
  71340. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  71341. /**
  71342. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  71343. * if vignetteEnabled is set to true.
  71344. */
  71345. get: function () {
  71346. return this.imageProcessingConfiguration.vignetteColor;
  71347. },
  71348. /**
  71349. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  71350. * if vignetteEnabled is set to true.
  71351. */
  71352. set: function (value) {
  71353. this.imageProcessingConfiguration.vignetteColor = value;
  71354. },
  71355. enumerable: true,
  71356. configurable: true
  71357. });
  71358. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  71359. /**
  71360. * Gets Camera field of view used by the Vignette effect.
  71361. */
  71362. get: function () {
  71363. return this.imageProcessingConfiguration.vignetteCameraFov;
  71364. },
  71365. /**
  71366. * Sets Camera field of view used by the Vignette effect.
  71367. */
  71368. set: function (value) {
  71369. this.imageProcessingConfiguration.vignetteCameraFov = value;
  71370. },
  71371. enumerable: true,
  71372. configurable: true
  71373. });
  71374. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  71375. /**
  71376. * Gets the vignette blend mode allowing different kind of effect.
  71377. */
  71378. get: function () {
  71379. return this.imageProcessingConfiguration.vignetteBlendMode;
  71380. },
  71381. /**
  71382. * Sets the vignette blend mode allowing different kind of effect.
  71383. */
  71384. set: function (value) {
  71385. this.imageProcessingConfiguration.vignetteBlendMode = value;
  71386. },
  71387. enumerable: true,
  71388. configurable: true
  71389. });
  71390. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  71391. /**
  71392. * Gets wether the vignette effect is enabled.
  71393. */
  71394. get: function () {
  71395. return this.imageProcessingConfiguration.vignetteEnabled;
  71396. },
  71397. /**
  71398. * Sets wether the vignette effect is enabled.
  71399. */
  71400. set: function (value) {
  71401. this.imageProcessingConfiguration.vignetteEnabled = value;
  71402. },
  71403. enumerable: true,
  71404. configurable: true
  71405. });
  71406. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainEnabled", {
  71407. /**
  71408. * Gets wether the grain effect is enabled.
  71409. */
  71410. get: function () {
  71411. return this.imageProcessingConfiguration.grainEnabled;
  71412. },
  71413. /**
  71414. * Sets wether the grain effect is enabled.
  71415. */
  71416. set: function (value) {
  71417. this.imageProcessingConfiguration.grainEnabled = value;
  71418. },
  71419. enumerable: true,
  71420. configurable: true
  71421. });
  71422. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainIntensity", {
  71423. /**
  71424. * Gets the grain effect's intensity.
  71425. */
  71426. get: function () {
  71427. return this.imageProcessingConfiguration.grainIntensity;
  71428. },
  71429. /**
  71430. * Sets the grain effect's intensity.
  71431. */
  71432. set: function (value) {
  71433. this.imageProcessingConfiguration.grainIntensity = value;
  71434. },
  71435. enumerable: true,
  71436. configurable: true
  71437. });
  71438. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainAnimated", {
  71439. /**
  71440. * Gets wether the grain effect is animated.
  71441. */
  71442. get: function () {
  71443. return this.imageProcessingConfiguration.grainAnimated;
  71444. },
  71445. /**
  71446. * Sets wether the grain effect is animated.
  71447. */
  71448. set: function (value) {
  71449. this.imageProcessingConfiguration.grainAnimated = value;
  71450. },
  71451. enumerable: true,
  71452. configurable: true
  71453. });
  71454. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  71455. /**
  71456. * Gets wether the input of the processing is in Gamma or Linear Space.
  71457. */
  71458. get: function () {
  71459. return this._fromLinearSpace;
  71460. },
  71461. /**
  71462. * Sets wether the input of the processing is in Gamma or Linear Space.
  71463. */
  71464. set: function (value) {
  71465. if (this._fromLinearSpace === value) {
  71466. return;
  71467. }
  71468. this._fromLinearSpace = value;
  71469. this._updateParameters();
  71470. },
  71471. enumerable: true,
  71472. configurable: true
  71473. });
  71474. ImageProcessingPostProcess.prototype.getClassName = function () {
  71475. return "ImageProcessingPostProcess";
  71476. };
  71477. ImageProcessingPostProcess.prototype._updateParameters = function () {
  71478. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  71479. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  71480. var defines = "";
  71481. for (var define in this._defines) {
  71482. if (this._defines[define]) {
  71483. defines += "#define " + define + ";\r\n";
  71484. }
  71485. }
  71486. var samplers = ["textureSampler"];
  71487. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  71488. var uniforms = ["scale"];
  71489. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  71490. this.updateEffect(defines, uniforms, samplers);
  71491. };
  71492. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  71493. _super.prototype.dispose.call(this, camera);
  71494. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  71495. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  71496. }
  71497. this.imageProcessingConfiguration.applyByPostProcess = false;
  71498. };
  71499. __decorate([
  71500. BABYLON.serialize()
  71501. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  71502. return ImageProcessingPostProcess;
  71503. }(BABYLON.PostProcess));
  71504. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  71505. })(BABYLON || (BABYLON = {}));
  71506. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  71507. "use strict";
  71508. var BABYLON;
  71509. (function (BABYLON) {
  71510. var Bone = /** @class */ (function (_super) {
  71511. __extends(Bone, _super);
  71512. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  71513. if (parentBone === void 0) { parentBone = null; }
  71514. if (localMatrix === void 0) { localMatrix = null; }
  71515. if (restPose === void 0) { restPose = null; }
  71516. if (baseMatrix === void 0) { baseMatrix = null; }
  71517. if (index === void 0) { index = null; }
  71518. var _this = _super.call(this, name, skeleton.getScene()) || this;
  71519. _this.name = name;
  71520. _this.children = new Array();
  71521. _this.animations = new Array();
  71522. // Set this value to map this bone to a different index in the transform matrices.
  71523. // Set this value to -1 to exclude the bone from the transform matrices.
  71524. _this._index = null;
  71525. _this._worldTransform = new BABYLON.Matrix();
  71526. _this._absoluteTransform = new BABYLON.Matrix();
  71527. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  71528. _this._scaleMatrix = BABYLON.Matrix.Identity();
  71529. _this._scaleVector = BABYLON.Vector3.One();
  71530. _this._negateScaleChildren = BABYLON.Vector3.One();
  71531. _this._scalingDeterminant = 1;
  71532. _this._skeleton = skeleton;
  71533. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  71534. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  71535. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  71536. _this._index = index;
  71537. skeleton.bones.push(_this);
  71538. _this.setParent(parentBone, false);
  71539. _this._updateDifferenceMatrix();
  71540. return _this;
  71541. }
  71542. Object.defineProperty(Bone.prototype, "_matrix", {
  71543. get: function () {
  71544. return this._localMatrix;
  71545. },
  71546. set: function (val) {
  71547. if (this._localMatrix) {
  71548. this._localMatrix.copyFrom(val);
  71549. }
  71550. else {
  71551. this._localMatrix = val;
  71552. }
  71553. },
  71554. enumerable: true,
  71555. configurable: true
  71556. });
  71557. // Members
  71558. Bone.prototype.getSkeleton = function () {
  71559. return this._skeleton;
  71560. };
  71561. Bone.prototype.getParent = function () {
  71562. return this._parent;
  71563. };
  71564. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  71565. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  71566. if (this._parent === parent) {
  71567. return;
  71568. }
  71569. if (this._parent) {
  71570. var index = this._parent.children.indexOf(this);
  71571. if (index !== -1) {
  71572. this._parent.children.splice(index, 1);
  71573. }
  71574. }
  71575. this._parent = parent;
  71576. if (this._parent) {
  71577. this._parent.children.push(this);
  71578. }
  71579. if (updateDifferenceMatrix) {
  71580. this._updateDifferenceMatrix();
  71581. }
  71582. };
  71583. Bone.prototype.getLocalMatrix = function () {
  71584. return this._localMatrix;
  71585. };
  71586. Bone.prototype.getBaseMatrix = function () {
  71587. return this._baseMatrix;
  71588. };
  71589. Bone.prototype.getRestPose = function () {
  71590. return this._restPose;
  71591. };
  71592. Bone.prototype.returnToRest = function () {
  71593. this.updateMatrix(this._restPose.clone());
  71594. };
  71595. Bone.prototype.getWorldMatrix = function () {
  71596. return this._worldTransform;
  71597. };
  71598. Bone.prototype.getInvertedAbsoluteTransform = function () {
  71599. return this._invertedAbsoluteTransform;
  71600. };
  71601. Bone.prototype.getAbsoluteTransform = function () {
  71602. return this._absoluteTransform;
  71603. };
  71604. Object.defineProperty(Bone.prototype, "position", {
  71605. // Properties (matches AbstractMesh properties)
  71606. get: function () {
  71607. return this.getPosition();
  71608. },
  71609. set: function (newPosition) {
  71610. this.setPosition(newPosition);
  71611. },
  71612. enumerable: true,
  71613. configurable: true
  71614. });
  71615. Object.defineProperty(Bone.prototype, "rotation", {
  71616. get: function () {
  71617. return this.getRotation();
  71618. },
  71619. set: function (newRotation) {
  71620. this.setRotation(newRotation);
  71621. },
  71622. enumerable: true,
  71623. configurable: true
  71624. });
  71625. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  71626. get: function () {
  71627. return this.getRotationQuaternion();
  71628. },
  71629. set: function (newRotation) {
  71630. this.setRotationQuaternion(newRotation);
  71631. },
  71632. enumerable: true,
  71633. configurable: true
  71634. });
  71635. Object.defineProperty(Bone.prototype, "scaling", {
  71636. get: function () {
  71637. return this.getScale();
  71638. },
  71639. set: function (newScaling) {
  71640. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  71641. },
  71642. enumerable: true,
  71643. configurable: true
  71644. });
  71645. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  71646. /**
  71647. * Gets the animation properties override
  71648. */
  71649. get: function () {
  71650. return this._skeleton.animationPropertiesOverride;
  71651. },
  71652. enumerable: true,
  71653. configurable: true
  71654. });
  71655. // Methods
  71656. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  71657. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  71658. this._baseMatrix = matrix.clone();
  71659. this._localMatrix = matrix.clone();
  71660. this._skeleton._markAsDirty();
  71661. if (updateDifferenceMatrix) {
  71662. this._updateDifferenceMatrix();
  71663. }
  71664. };
  71665. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  71666. if (!rootMatrix) {
  71667. rootMatrix = this._baseMatrix;
  71668. }
  71669. if (this._parent) {
  71670. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  71671. }
  71672. else {
  71673. this._absoluteTransform.copyFrom(rootMatrix);
  71674. }
  71675. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  71676. for (var index = 0; index < this.children.length; index++) {
  71677. this.children[index]._updateDifferenceMatrix();
  71678. }
  71679. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  71680. };
  71681. Bone.prototype.markAsDirty = function () {
  71682. this._currentRenderId++;
  71683. this._skeleton._markAsDirty();
  71684. };
  71685. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  71686. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  71687. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  71688. // all animation may be coming from a library skeleton, so may need to create animation
  71689. if (this.animations.length === 0) {
  71690. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  71691. this.animations[0].setKeys([]);
  71692. }
  71693. // get animation info / verify there is such a range from the source bone
  71694. var sourceRange = source.animations[0].getRange(rangeName);
  71695. if (!sourceRange) {
  71696. return false;
  71697. }
  71698. var from = sourceRange.from;
  71699. var to = sourceRange.to;
  71700. var sourceKeys = source.animations[0].getKeys();
  71701. // rescaling prep
  71702. var sourceBoneLength = source.length;
  71703. var sourceParent = source.getParent();
  71704. var parent = this.getParent();
  71705. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  71706. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  71707. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  71708. var destKeys = this.animations[0].getKeys();
  71709. // loop vars declaration
  71710. var orig;
  71711. var origTranslation;
  71712. var mat;
  71713. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  71714. orig = sourceKeys[key];
  71715. if (orig.frame >= from && orig.frame <= to) {
  71716. if (rescaleAsRequired) {
  71717. mat = orig.value.clone();
  71718. // scale based on parent ratio, when bone has parent
  71719. if (parentScalingReqd) {
  71720. origTranslation = mat.getTranslation();
  71721. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  71722. // scale based on skeleton dimension ratio when root bone, and value is passed
  71723. }
  71724. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  71725. origTranslation = mat.getTranslation();
  71726. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  71727. // use original when root bone, and no data for skelDimensionsRatio
  71728. }
  71729. else {
  71730. mat = orig.value;
  71731. }
  71732. }
  71733. else {
  71734. mat = orig.value;
  71735. }
  71736. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  71737. }
  71738. }
  71739. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  71740. return true;
  71741. };
  71742. /**
  71743. * Translate the bone in local or world space.
  71744. * @param vec The amount to translate the bone.
  71745. * @param space The space that the translation is in.
  71746. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71747. */
  71748. Bone.prototype.translate = function (vec, space, mesh) {
  71749. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71750. var lm = this.getLocalMatrix();
  71751. if (space == BABYLON.Space.LOCAL) {
  71752. lm.m[12] += vec.x;
  71753. lm.m[13] += vec.y;
  71754. lm.m[14] += vec.z;
  71755. }
  71756. else {
  71757. var wm = null;
  71758. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71759. if (mesh) {
  71760. wm = mesh.getWorldMatrix();
  71761. }
  71762. this._skeleton.computeAbsoluteTransforms();
  71763. var tmat = Bone._tmpMats[0];
  71764. var tvec = Bone._tmpVecs[0];
  71765. if (this._parent) {
  71766. if (mesh && wm) {
  71767. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71768. tmat.multiplyToRef(wm, tmat);
  71769. }
  71770. else {
  71771. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71772. }
  71773. }
  71774. tmat.m[12] = 0;
  71775. tmat.m[13] = 0;
  71776. tmat.m[14] = 0;
  71777. tmat.invert();
  71778. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  71779. lm.m[12] += tvec.x;
  71780. lm.m[13] += tvec.y;
  71781. lm.m[14] += tvec.z;
  71782. }
  71783. this.markAsDirty();
  71784. };
  71785. /**
  71786. * Set the postion of the bone in local or world space.
  71787. * @param position The position to set the bone.
  71788. * @param space The space that the position is in.
  71789. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71790. */
  71791. Bone.prototype.setPosition = function (position, space, mesh) {
  71792. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71793. var lm = this.getLocalMatrix();
  71794. if (space == BABYLON.Space.LOCAL) {
  71795. lm.m[12] = position.x;
  71796. lm.m[13] = position.y;
  71797. lm.m[14] = position.z;
  71798. }
  71799. else {
  71800. var wm = null;
  71801. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71802. if (mesh) {
  71803. wm = mesh.getWorldMatrix();
  71804. }
  71805. this._skeleton.computeAbsoluteTransforms();
  71806. var tmat = Bone._tmpMats[0];
  71807. var vec = Bone._tmpVecs[0];
  71808. if (this._parent) {
  71809. if (mesh && wm) {
  71810. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71811. tmat.multiplyToRef(wm, tmat);
  71812. }
  71813. else {
  71814. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71815. }
  71816. }
  71817. tmat.invert();
  71818. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  71819. lm.m[12] = vec.x;
  71820. lm.m[13] = vec.y;
  71821. lm.m[14] = vec.z;
  71822. }
  71823. this.markAsDirty();
  71824. };
  71825. /**
  71826. * Set the absolute postion of the bone (world space).
  71827. * @param position The position to set the bone.
  71828. * @param mesh The mesh that this bone is attached to.
  71829. */
  71830. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  71831. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  71832. };
  71833. /**
  71834. * Set the scale of the bone on the x, y and z axes.
  71835. * @param x The scale of the bone on the x axis.
  71836. * @param x The scale of the bone on the y axis.
  71837. * @param z The scale of the bone on the z axis.
  71838. * @param scaleChildren Set this to true if children of the bone should be scaled.
  71839. */
  71840. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  71841. if (scaleChildren === void 0) { scaleChildren = false; }
  71842. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  71843. if (!scaleChildren) {
  71844. this._negateScaleChildren.x = 1 / x;
  71845. this._negateScaleChildren.y = 1 / y;
  71846. this._negateScaleChildren.z = 1 / z;
  71847. }
  71848. this._syncScaleVector();
  71849. }
  71850. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  71851. };
  71852. /**
  71853. * Scale the bone on the x, y and z axes.
  71854. * @param x The amount to scale the bone on the x axis.
  71855. * @param x The amount to scale the bone on the y axis.
  71856. * @param z The amount to scale the bone on the z axis.
  71857. * @param scaleChildren Set this to true if children of the bone should be scaled.
  71858. */
  71859. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  71860. if (scaleChildren === void 0) { scaleChildren = false; }
  71861. var locMat = this.getLocalMatrix();
  71862. var origLocMat = Bone._tmpMats[0];
  71863. origLocMat.copyFrom(locMat);
  71864. var origLocMatInv = Bone._tmpMats[1];
  71865. origLocMatInv.copyFrom(origLocMat);
  71866. origLocMatInv.invert();
  71867. var scaleMat = Bone._tmpMats[2];
  71868. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  71869. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  71870. this._scaleVector.x *= x;
  71871. this._scaleVector.y *= y;
  71872. this._scaleVector.z *= z;
  71873. locMat.multiplyToRef(origLocMatInv, locMat);
  71874. locMat.multiplyToRef(scaleMat, locMat);
  71875. locMat.multiplyToRef(origLocMat, locMat);
  71876. var parent = this.getParent();
  71877. if (parent) {
  71878. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  71879. }
  71880. else {
  71881. this.getAbsoluteTransform().copyFrom(locMat);
  71882. }
  71883. var len = this.children.length;
  71884. scaleMat.invert();
  71885. for (var i = 0; i < len; i++) {
  71886. var child = this.children[i];
  71887. var cm = child.getLocalMatrix();
  71888. cm.multiplyToRef(scaleMat, cm);
  71889. var lm = child.getLocalMatrix();
  71890. lm.m[12] *= x;
  71891. lm.m[13] *= y;
  71892. lm.m[14] *= z;
  71893. }
  71894. this.computeAbsoluteTransforms();
  71895. if (scaleChildren) {
  71896. for (var i = 0; i < len; i++) {
  71897. this.children[i].scale(x, y, z, scaleChildren);
  71898. }
  71899. }
  71900. this.markAsDirty();
  71901. };
  71902. /**
  71903. * Set the yaw, pitch, and roll of the bone in local or world space.
  71904. * @param yaw The rotation of the bone on the y axis.
  71905. * @param pitch The rotation of the bone on the x axis.
  71906. * @param roll The rotation of the bone on the z axis.
  71907. * @param space The space that the axes of rotation are in.
  71908. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71909. */
  71910. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  71911. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71912. var rotMat = Bone._tmpMats[0];
  71913. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  71914. var rotMatInv = Bone._tmpMats[1];
  71915. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71916. rotMatInv.multiplyToRef(rotMat, rotMat);
  71917. this._rotateWithMatrix(rotMat, space, mesh);
  71918. };
  71919. /**
  71920. * Rotate the bone on an axis in local or world space.
  71921. * @param axis The axis to rotate the bone on.
  71922. * @param amount The amount to rotate the bone.
  71923. * @param space The space that the axis is in.
  71924. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71925. */
  71926. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  71927. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71928. var rmat = Bone._tmpMats[0];
  71929. rmat.m[12] = 0;
  71930. rmat.m[13] = 0;
  71931. rmat.m[14] = 0;
  71932. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  71933. this._rotateWithMatrix(rmat, space, mesh);
  71934. };
  71935. /**
  71936. * Set the rotation of the bone to a particular axis angle in local or world space.
  71937. * @param axis The axis to rotate the bone on.
  71938. * @param angle The angle that the bone should be rotated to.
  71939. * @param space The space that the axis is in.
  71940. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71941. */
  71942. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  71943. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71944. var rotMat = Bone._tmpMats[0];
  71945. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  71946. var rotMatInv = Bone._tmpMats[1];
  71947. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71948. rotMatInv.multiplyToRef(rotMat, rotMat);
  71949. this._rotateWithMatrix(rotMat, space, mesh);
  71950. };
  71951. /**
  71952. * Set the euler rotation of the bone in local of world space.
  71953. * @param rotation The euler rotation that the bone should be set to.
  71954. * @param space The space that the rotation is in.
  71955. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71956. */
  71957. Bone.prototype.setRotation = function (rotation, space, mesh) {
  71958. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71959. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  71960. };
  71961. /**
  71962. * Set the quaternion rotation of the bone in local of world space.
  71963. * @param quat The quaternion rotation that the bone should be set to.
  71964. * @param space The space that the rotation is in.
  71965. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71966. */
  71967. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  71968. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71969. var rotMatInv = Bone._tmpMats[0];
  71970. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71971. var rotMat = Bone._tmpMats[1];
  71972. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  71973. rotMatInv.multiplyToRef(rotMat, rotMat);
  71974. this._rotateWithMatrix(rotMat, space, mesh);
  71975. };
  71976. /**
  71977. * Set the rotation matrix of the bone in local of world space.
  71978. * @param rotMat The rotation matrix that the bone should be set to.
  71979. * @param space The space that the rotation is in.
  71980. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71981. */
  71982. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  71983. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71984. var rotMatInv = Bone._tmpMats[0];
  71985. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71986. var rotMat2 = Bone._tmpMats[1];
  71987. rotMat2.copyFrom(rotMat);
  71988. rotMatInv.multiplyToRef(rotMat, rotMat2);
  71989. this._rotateWithMatrix(rotMat2, space, mesh);
  71990. };
  71991. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  71992. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71993. var lmat = this.getLocalMatrix();
  71994. var lx = lmat.m[12];
  71995. var ly = lmat.m[13];
  71996. var lz = lmat.m[14];
  71997. var parent = this.getParent();
  71998. var parentScale = Bone._tmpMats[3];
  71999. var parentScaleInv = Bone._tmpMats[4];
  72000. if (parent) {
  72001. if (space == BABYLON.Space.WORLD) {
  72002. if (mesh) {
  72003. parentScale.copyFrom(mesh.getWorldMatrix());
  72004. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  72005. }
  72006. else {
  72007. parentScale.copyFrom(parent.getAbsoluteTransform());
  72008. }
  72009. }
  72010. else {
  72011. parentScale = parent._scaleMatrix;
  72012. }
  72013. parentScaleInv.copyFrom(parentScale);
  72014. parentScaleInv.invert();
  72015. lmat.multiplyToRef(parentScale, lmat);
  72016. lmat.multiplyToRef(rmat, lmat);
  72017. lmat.multiplyToRef(parentScaleInv, lmat);
  72018. }
  72019. else {
  72020. if (space == BABYLON.Space.WORLD && mesh) {
  72021. parentScale.copyFrom(mesh.getWorldMatrix());
  72022. parentScaleInv.copyFrom(parentScale);
  72023. parentScaleInv.invert();
  72024. lmat.multiplyToRef(parentScale, lmat);
  72025. lmat.multiplyToRef(rmat, lmat);
  72026. lmat.multiplyToRef(parentScaleInv, lmat);
  72027. }
  72028. else {
  72029. lmat.multiplyToRef(rmat, lmat);
  72030. }
  72031. }
  72032. lmat.m[12] = lx;
  72033. lmat.m[13] = ly;
  72034. lmat.m[14] = lz;
  72035. this.computeAbsoluteTransforms();
  72036. this.markAsDirty();
  72037. };
  72038. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  72039. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72040. if (space == BABYLON.Space.WORLD) {
  72041. var scaleMatrix = Bone._tmpMats[2];
  72042. scaleMatrix.copyFrom(this._scaleMatrix);
  72043. rotMatInv.copyFrom(this.getAbsoluteTransform());
  72044. if (mesh) {
  72045. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  72046. var meshScale = Bone._tmpMats[3];
  72047. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  72048. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  72049. }
  72050. rotMatInv.invert();
  72051. scaleMatrix.m[0] *= this._scalingDeterminant;
  72052. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  72053. }
  72054. else {
  72055. rotMatInv.copyFrom(this.getLocalMatrix());
  72056. rotMatInv.invert();
  72057. var scaleMatrix = Bone._tmpMats[2];
  72058. scaleMatrix.copyFrom(this._scaleMatrix);
  72059. if (this._parent) {
  72060. var pscaleMatrix = Bone._tmpMats[3];
  72061. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  72062. pscaleMatrix.invert();
  72063. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  72064. }
  72065. else {
  72066. scaleMatrix.m[0] *= this._scalingDeterminant;
  72067. }
  72068. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  72069. }
  72070. };
  72071. /**
  72072. * Get the scale of the bone
  72073. * @returns the scale of the bone
  72074. */
  72075. Bone.prototype.getScale = function () {
  72076. return this._scaleVector.clone();
  72077. };
  72078. /**
  72079. * Copy the scale of the bone to a vector3.
  72080. * @param result The vector3 to copy the scale to
  72081. */
  72082. Bone.prototype.getScaleToRef = function (result) {
  72083. result.copyFrom(this._scaleVector);
  72084. };
  72085. /**
  72086. * Get the position of the bone in local or world space.
  72087. * @param space The space that the returned position is in.
  72088. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72089. * @returns The position of the bone
  72090. */
  72091. Bone.prototype.getPosition = function (space, mesh) {
  72092. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72093. if (mesh === void 0) { mesh = null; }
  72094. var pos = BABYLON.Vector3.Zero();
  72095. this.getPositionToRef(space, mesh, pos);
  72096. return pos;
  72097. };
  72098. /**
  72099. * Copy the position of the bone to a vector3 in local or world space.
  72100. * @param space The space that the returned position is in.
  72101. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72102. * @param result The vector3 to copy the position to.
  72103. */
  72104. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  72105. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72106. if (space == BABYLON.Space.LOCAL) {
  72107. var lm = this.getLocalMatrix();
  72108. result.x = lm.m[12];
  72109. result.y = lm.m[13];
  72110. result.z = lm.m[14];
  72111. }
  72112. else {
  72113. var wm = null;
  72114. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72115. if (mesh) {
  72116. wm = mesh.getWorldMatrix();
  72117. }
  72118. this._skeleton.computeAbsoluteTransforms();
  72119. var tmat = Bone._tmpMats[0];
  72120. if (mesh && wm) {
  72121. tmat.copyFrom(this.getAbsoluteTransform());
  72122. tmat.multiplyToRef(wm, tmat);
  72123. }
  72124. else {
  72125. tmat = this.getAbsoluteTransform();
  72126. }
  72127. result.x = tmat.m[12];
  72128. result.y = tmat.m[13];
  72129. result.z = tmat.m[14];
  72130. }
  72131. };
  72132. /**
  72133. * Get the absolute position of the bone (world space).
  72134. * @param mesh The mesh that this bone is attached to.
  72135. * @returns The absolute position of the bone
  72136. */
  72137. Bone.prototype.getAbsolutePosition = function (mesh) {
  72138. if (mesh === void 0) { mesh = null; }
  72139. var pos = BABYLON.Vector3.Zero();
  72140. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  72141. return pos;
  72142. };
  72143. /**
  72144. * Copy the absolute position of the bone (world space) to the result param.
  72145. * @param mesh The mesh that this bone is attached to.
  72146. * @param result The vector3 to copy the absolute position to.
  72147. */
  72148. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  72149. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  72150. };
  72151. /**
  72152. * Compute the absolute transforms of this bone and its children.
  72153. */
  72154. Bone.prototype.computeAbsoluteTransforms = function () {
  72155. if (this._parent) {
  72156. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  72157. }
  72158. else {
  72159. this._absoluteTransform.copyFrom(this._localMatrix);
  72160. var poseMatrix = this._skeleton.getPoseMatrix();
  72161. if (poseMatrix) {
  72162. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  72163. }
  72164. }
  72165. var children = this.children;
  72166. var len = children.length;
  72167. for (var i = 0; i < len; i++) {
  72168. children[i].computeAbsoluteTransforms();
  72169. }
  72170. };
  72171. Bone.prototype._syncScaleVector = function () {
  72172. var lm = this.getLocalMatrix();
  72173. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  72174. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  72175. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  72176. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  72177. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  72178. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  72179. this._scaleVector.x = xs * Math.sqrt(xsq);
  72180. this._scaleVector.y = ys * Math.sqrt(ysq);
  72181. this._scaleVector.z = zs * Math.sqrt(zsq);
  72182. if (this._parent) {
  72183. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  72184. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  72185. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  72186. }
  72187. 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);
  72188. };
  72189. /**
  72190. * Get the world direction from an axis that is in the local space of the bone.
  72191. * @param localAxis The local direction that is used to compute the world direction.
  72192. * @param mesh The mesh that this bone is attached to.
  72193. * @returns The world direction
  72194. */
  72195. Bone.prototype.getDirection = function (localAxis, mesh) {
  72196. if (mesh === void 0) { mesh = null; }
  72197. var result = BABYLON.Vector3.Zero();
  72198. this.getDirectionToRef(localAxis, mesh, result);
  72199. return result;
  72200. };
  72201. /**
  72202. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  72203. * @param localAxis The local direction that is used to compute the world direction.
  72204. * @param mesh The mesh that this bone is attached to.
  72205. * @param result The vector3 that the world direction will be copied to.
  72206. */
  72207. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  72208. if (mesh === void 0) { mesh = null; }
  72209. var wm = null;
  72210. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72211. if (mesh) {
  72212. wm = mesh.getWorldMatrix();
  72213. }
  72214. this._skeleton.computeAbsoluteTransforms();
  72215. var mat = Bone._tmpMats[0];
  72216. mat.copyFrom(this.getAbsoluteTransform());
  72217. if (mesh && wm) {
  72218. mat.multiplyToRef(wm, mat);
  72219. }
  72220. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  72221. result.normalize();
  72222. };
  72223. /**
  72224. * Get the euler rotation of the bone in local or world space.
  72225. * @param space The space that the rotation should be in.
  72226. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72227. * @returns The euler rotation
  72228. */
  72229. Bone.prototype.getRotation = function (space, mesh) {
  72230. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72231. if (mesh === void 0) { mesh = null; }
  72232. var result = BABYLON.Vector3.Zero();
  72233. this.getRotationToRef(space, mesh, result);
  72234. return result;
  72235. };
  72236. /**
  72237. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  72238. * @param space The space that the rotation should be in.
  72239. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72240. * @param result The vector3 that the rotation should be copied to.
  72241. */
  72242. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  72243. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72244. if (mesh === void 0) { mesh = null; }
  72245. var quat = Bone._tmpQuat;
  72246. this.getRotationQuaternionToRef(space, mesh, quat);
  72247. quat.toEulerAnglesToRef(result);
  72248. };
  72249. /**
  72250. * Get the quaternion rotation of the bone in either local or world space.
  72251. * @param space The space that the rotation should be in.
  72252. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72253. * @returns The quaternion rotation
  72254. */
  72255. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  72256. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72257. if (mesh === void 0) { mesh = null; }
  72258. var result = BABYLON.Quaternion.Identity();
  72259. this.getRotationQuaternionToRef(space, mesh, result);
  72260. return result;
  72261. };
  72262. /**
  72263. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  72264. * @param space The space that the rotation should be in.
  72265. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72266. * @param result The quaternion that the rotation should be copied to.
  72267. */
  72268. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  72269. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72270. if (mesh === void 0) { mesh = null; }
  72271. if (space == BABYLON.Space.LOCAL) {
  72272. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  72273. }
  72274. else {
  72275. var mat = Bone._tmpMats[0];
  72276. var amat = this.getAbsoluteTransform();
  72277. if (mesh) {
  72278. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  72279. }
  72280. else {
  72281. mat.copyFrom(amat);
  72282. }
  72283. mat.m[0] *= this._scalingDeterminant;
  72284. mat.m[1] *= this._scalingDeterminant;
  72285. mat.m[2] *= this._scalingDeterminant;
  72286. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  72287. }
  72288. };
  72289. /**
  72290. * Get the rotation matrix of the bone in local or world space.
  72291. * @param space The space that the rotation should be in.
  72292. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72293. * @returns The rotation matrix
  72294. */
  72295. Bone.prototype.getRotationMatrix = function (space, mesh) {
  72296. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72297. var result = BABYLON.Matrix.Identity();
  72298. this.getRotationMatrixToRef(space, mesh, result);
  72299. return result;
  72300. };
  72301. /**
  72302. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  72303. * @param space The space that the rotation should be in.
  72304. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72305. * @param result The quaternion that the rotation should be copied to.
  72306. */
  72307. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  72308. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72309. if (space == BABYLON.Space.LOCAL) {
  72310. this.getLocalMatrix().getRotationMatrixToRef(result);
  72311. }
  72312. else {
  72313. var mat = Bone._tmpMats[0];
  72314. var amat = this.getAbsoluteTransform();
  72315. if (mesh) {
  72316. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  72317. }
  72318. else {
  72319. mat.copyFrom(amat);
  72320. }
  72321. mat.m[0] *= this._scalingDeterminant;
  72322. mat.m[1] *= this._scalingDeterminant;
  72323. mat.m[2] *= this._scalingDeterminant;
  72324. mat.getRotationMatrixToRef(result);
  72325. }
  72326. };
  72327. /**
  72328. * Get the world position of a point that is in the local space of the bone.
  72329. * @param position The local position
  72330. * @param mesh The mesh that this bone is attached to.
  72331. * @returns The world position
  72332. */
  72333. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  72334. if (mesh === void 0) { mesh = null; }
  72335. var result = BABYLON.Vector3.Zero();
  72336. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  72337. return result;
  72338. };
  72339. /**
  72340. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  72341. * @param position The local position
  72342. * @param mesh The mesh that this bone is attached to.
  72343. * @param result The vector3 that the world position should be copied to.
  72344. */
  72345. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  72346. if (mesh === void 0) { mesh = null; }
  72347. var wm = null;
  72348. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72349. if (mesh) {
  72350. wm = mesh.getWorldMatrix();
  72351. }
  72352. this._skeleton.computeAbsoluteTransforms();
  72353. var tmat = Bone._tmpMats[0];
  72354. if (mesh && wm) {
  72355. tmat.copyFrom(this.getAbsoluteTransform());
  72356. tmat.multiplyToRef(wm, tmat);
  72357. }
  72358. else {
  72359. tmat = this.getAbsoluteTransform();
  72360. }
  72361. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  72362. };
  72363. /**
  72364. * Get the local position of a point that is in world space.
  72365. * @param position The world position
  72366. * @param mesh The mesh that this bone is attached to.
  72367. * @returns The local position
  72368. */
  72369. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  72370. if (mesh === void 0) { mesh = null; }
  72371. var result = BABYLON.Vector3.Zero();
  72372. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  72373. return result;
  72374. };
  72375. /**
  72376. * Get the local position of a point that is in world space and copy it to the result param.
  72377. * @param position The world position
  72378. * @param mesh The mesh that this bone is attached to.
  72379. * @param result The vector3 that the local position should be copied to.
  72380. */
  72381. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  72382. if (mesh === void 0) { mesh = null; }
  72383. var wm = null;
  72384. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72385. if (mesh) {
  72386. wm = mesh.getWorldMatrix();
  72387. }
  72388. this._skeleton.computeAbsoluteTransforms();
  72389. var tmat = Bone._tmpMats[0];
  72390. tmat.copyFrom(this.getAbsoluteTransform());
  72391. if (mesh && wm) {
  72392. tmat.multiplyToRef(wm, tmat);
  72393. }
  72394. tmat.invert();
  72395. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  72396. };
  72397. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72398. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  72399. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72400. return Bone;
  72401. }(BABYLON.Node));
  72402. BABYLON.Bone = Bone;
  72403. })(BABYLON || (BABYLON = {}));
  72404. //# sourceMappingURL=babylon.bone.js.map
  72405. "use strict";
  72406. var BABYLON;
  72407. (function (BABYLON) {
  72408. var BoneIKController = /** @class */ (function () {
  72409. function BoneIKController(mesh, bone, options) {
  72410. this.targetPosition = BABYLON.Vector3.Zero();
  72411. this.poleTargetPosition = BABYLON.Vector3.Zero();
  72412. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  72413. this.poleAngle = 0;
  72414. this.slerpAmount = 1;
  72415. this._bone1Quat = BABYLON.Quaternion.Identity();
  72416. this._bone1Mat = BABYLON.Matrix.Identity();
  72417. this._bone2Ang = Math.PI;
  72418. this._maxAngle = Math.PI;
  72419. this._rightHandedSystem = false;
  72420. this._bendAxis = BABYLON.Vector3.Right();
  72421. this._slerping = false;
  72422. this._adjustRoll = 0;
  72423. this._bone2 = bone;
  72424. this._bone1 = bone.getParent();
  72425. if (!this._bone1) {
  72426. return;
  72427. }
  72428. this.mesh = mesh;
  72429. var bonePos = bone.getPosition();
  72430. if (bone.getAbsoluteTransform().determinant() > 0) {
  72431. this._rightHandedSystem = true;
  72432. this._bendAxis.x = 0;
  72433. this._bendAxis.y = 0;
  72434. this._bendAxis.z = -1;
  72435. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  72436. this._adjustRoll = Math.PI * .5;
  72437. this._bendAxis.z = 1;
  72438. }
  72439. }
  72440. if (this._bone1.length) {
  72441. var boneScale1 = this._bone1.getScale();
  72442. var boneScale2 = this._bone2.getScale();
  72443. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  72444. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  72445. }
  72446. else if (this._bone1.children[0]) {
  72447. mesh.computeWorldMatrix(true);
  72448. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  72449. var pos2 = this._bone2.getAbsolutePosition(mesh);
  72450. var pos3 = this._bone1.getAbsolutePosition(mesh);
  72451. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  72452. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  72453. }
  72454. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  72455. this.maxAngle = Math.PI;
  72456. if (options) {
  72457. if (options.targetMesh) {
  72458. this.targetMesh = options.targetMesh;
  72459. this.targetMesh.computeWorldMatrix(true);
  72460. }
  72461. if (options.poleTargetMesh) {
  72462. this.poleTargetMesh = options.poleTargetMesh;
  72463. this.poleTargetMesh.computeWorldMatrix(true);
  72464. }
  72465. else if (options.poleTargetBone) {
  72466. this.poleTargetBone = options.poleTargetBone;
  72467. }
  72468. else if (this._bone1.getParent()) {
  72469. this.poleTargetBone = this._bone1.getParent();
  72470. }
  72471. if (options.poleTargetLocalOffset) {
  72472. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  72473. }
  72474. if (options.poleAngle) {
  72475. this.poleAngle = options.poleAngle;
  72476. }
  72477. if (options.bendAxis) {
  72478. this._bendAxis.copyFrom(options.bendAxis);
  72479. }
  72480. if (options.maxAngle) {
  72481. this.maxAngle = options.maxAngle;
  72482. }
  72483. if (options.slerpAmount) {
  72484. this.slerpAmount = options.slerpAmount;
  72485. }
  72486. }
  72487. }
  72488. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  72489. get: function () {
  72490. return this._maxAngle;
  72491. },
  72492. set: function (value) {
  72493. this._setMaxAngle(value);
  72494. },
  72495. enumerable: true,
  72496. configurable: true
  72497. });
  72498. BoneIKController.prototype._setMaxAngle = function (ang) {
  72499. if (ang < 0) {
  72500. ang = 0;
  72501. }
  72502. if (ang > Math.PI || ang == undefined) {
  72503. ang = Math.PI;
  72504. }
  72505. this._maxAngle = ang;
  72506. var a = this._bone1Length;
  72507. var b = this._bone2Length;
  72508. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  72509. };
  72510. BoneIKController.prototype.update = function () {
  72511. var bone1 = this._bone1;
  72512. if (!bone1) {
  72513. return;
  72514. }
  72515. var target = this.targetPosition;
  72516. var poleTarget = this.poleTargetPosition;
  72517. var mat1 = BoneIKController._tmpMats[0];
  72518. var mat2 = BoneIKController._tmpMats[1];
  72519. if (this.targetMesh) {
  72520. target.copyFrom(this.targetMesh.getAbsolutePosition());
  72521. }
  72522. if (this.poleTargetBone) {
  72523. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  72524. }
  72525. else if (this.poleTargetMesh) {
  72526. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  72527. }
  72528. var bonePos = BoneIKController._tmpVecs[0];
  72529. var zaxis = BoneIKController._tmpVecs[1];
  72530. var xaxis = BoneIKController._tmpVecs[2];
  72531. var yaxis = BoneIKController._tmpVecs[3];
  72532. var upAxis = BoneIKController._tmpVecs[4];
  72533. var _tmpQuat = BoneIKController._tmpQuat;
  72534. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  72535. poleTarget.subtractToRef(bonePos, upAxis);
  72536. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  72537. upAxis.y = 1;
  72538. }
  72539. else {
  72540. upAxis.normalize();
  72541. }
  72542. target.subtractToRef(bonePos, yaxis);
  72543. yaxis.normalize();
  72544. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  72545. zaxis.normalize();
  72546. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  72547. xaxis.normalize();
  72548. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  72549. var a = this._bone1Length;
  72550. var b = this._bone2Length;
  72551. var c = BABYLON.Vector3.Distance(bonePos, target);
  72552. if (this._maxReach > 0) {
  72553. c = Math.min(this._maxReach, c);
  72554. }
  72555. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  72556. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  72557. if (acosa > 1) {
  72558. acosa = 1;
  72559. }
  72560. if (acosb > 1) {
  72561. acosb = 1;
  72562. }
  72563. if (acosa < -1) {
  72564. acosa = -1;
  72565. }
  72566. if (acosb < -1) {
  72567. acosb = -1;
  72568. }
  72569. var angA = Math.acos(acosa);
  72570. var angB = Math.acos(acosb);
  72571. var angC = -angA - angB;
  72572. if (this._rightHandedSystem) {
  72573. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  72574. mat2.multiplyToRef(mat1, mat1);
  72575. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  72576. mat2.multiplyToRef(mat1, mat1);
  72577. }
  72578. else {
  72579. var _tmpVec = BoneIKController._tmpVecs[5];
  72580. _tmpVec.copyFrom(this._bendAxis);
  72581. _tmpVec.x *= -1;
  72582. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  72583. mat2.multiplyToRef(mat1, mat1);
  72584. }
  72585. if (this.poleAngle) {
  72586. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  72587. mat1.multiplyToRef(mat2, mat1);
  72588. }
  72589. if (this._bone1) {
  72590. if (this.slerpAmount < 1) {
  72591. if (!this._slerping) {
  72592. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  72593. }
  72594. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  72595. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  72596. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  72597. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  72598. this._slerping = true;
  72599. }
  72600. else {
  72601. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  72602. this._bone1Mat.copyFrom(mat1);
  72603. this._slerping = false;
  72604. }
  72605. }
  72606. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  72607. this._bone2Ang = angC;
  72608. };
  72609. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72610. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  72611. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72612. return BoneIKController;
  72613. }());
  72614. BABYLON.BoneIKController = BoneIKController;
  72615. })(BABYLON || (BABYLON = {}));
  72616. //# sourceMappingURL=babylon.boneIKController.js.map
  72617. "use strict";
  72618. var BABYLON;
  72619. (function (BABYLON) {
  72620. var BoneLookController = /** @class */ (function () {
  72621. /**
  72622. * Create a BoneLookController
  72623. * @param mesh the mesh that the bone belongs to
  72624. * @param bone the bone that will be looking to the target
  72625. * @param target the target Vector3 to look at
  72626. * @param settings optional settings:
  72627. * - maxYaw: the maximum angle the bone will yaw to
  72628. * - minYaw: the minimum angle the bone will yaw to
  72629. * - maxPitch: the maximum angle the bone will pitch to
  72630. * - minPitch: the minimum angle the bone will yaw to
  72631. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  72632. * - upAxis: the up axis of the coordinate system
  72633. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  72634. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  72635. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  72636. * - adjustYaw: used to make an adjustment to the yaw of the bone
  72637. * - adjustPitch: used to make an adjustment to the pitch of the bone
  72638. * - adjustRoll: used to make an adjustment to the roll of the bone
  72639. **/
  72640. function BoneLookController(mesh, bone, target, options) {
  72641. /**
  72642. * The up axis of the coordinate system that is used when the bone is rotated.
  72643. */
  72644. this.upAxis = BABYLON.Vector3.Up();
  72645. /**
  72646. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  72647. */
  72648. this.upAxisSpace = BABYLON.Space.LOCAL;
  72649. /**
  72650. * Used to make an adjustment to the yaw of the bone.
  72651. */
  72652. this.adjustYaw = 0;
  72653. /**
  72654. * Used to make an adjustment to the pitch of the bone.
  72655. */
  72656. this.adjustPitch = 0;
  72657. /**
  72658. * Used to make an adjustment to the roll of the bone.
  72659. */
  72660. this.adjustRoll = 0;
  72661. /**
  72662. * 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).
  72663. */
  72664. this.slerpAmount = 1;
  72665. this._boneQuat = BABYLON.Quaternion.Identity();
  72666. this._slerping = false;
  72667. this._firstFrameSkipped = false;
  72668. this._fowardAxis = BABYLON.Vector3.Forward();
  72669. this.mesh = mesh;
  72670. this.bone = bone;
  72671. this.target = target;
  72672. if (options) {
  72673. if (options.adjustYaw) {
  72674. this.adjustYaw = options.adjustYaw;
  72675. }
  72676. if (options.adjustPitch) {
  72677. this.adjustPitch = options.adjustPitch;
  72678. }
  72679. if (options.adjustRoll) {
  72680. this.adjustRoll = options.adjustRoll;
  72681. }
  72682. if (options.maxYaw != null) {
  72683. this.maxYaw = options.maxYaw;
  72684. }
  72685. else {
  72686. this.maxYaw = Math.PI;
  72687. }
  72688. if (options.minYaw != null) {
  72689. this.minYaw = options.minYaw;
  72690. }
  72691. else {
  72692. this.minYaw = -Math.PI;
  72693. }
  72694. if (options.maxPitch != null) {
  72695. this.maxPitch = options.maxPitch;
  72696. }
  72697. else {
  72698. this.maxPitch = Math.PI;
  72699. }
  72700. if (options.minPitch != null) {
  72701. this.minPitch = options.minPitch;
  72702. }
  72703. else {
  72704. this.minPitch = -Math.PI;
  72705. }
  72706. if (options.slerpAmount != null) {
  72707. this.slerpAmount = options.slerpAmount;
  72708. }
  72709. if (options.upAxis != null) {
  72710. this.upAxis = options.upAxis;
  72711. }
  72712. if (options.upAxisSpace != null) {
  72713. this.upAxisSpace = options.upAxisSpace;
  72714. }
  72715. if (options.yawAxis != null || options.pitchAxis != null) {
  72716. var newYawAxis = BABYLON.Axis.Y;
  72717. var newPitchAxis = BABYLON.Axis.X;
  72718. if (options.yawAxis != null) {
  72719. newYawAxis = options.yawAxis.clone();
  72720. newYawAxis.normalize();
  72721. }
  72722. if (options.pitchAxis != null) {
  72723. newPitchAxis = options.pitchAxis.clone();
  72724. newPitchAxis.normalize();
  72725. }
  72726. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  72727. this._transformYawPitch = BABYLON.Matrix.Identity();
  72728. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  72729. this._transformYawPitchInv = this._transformYawPitch.clone();
  72730. this._transformYawPitch.invert();
  72731. }
  72732. }
  72733. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  72734. this.upAxisSpace = BABYLON.Space.LOCAL;
  72735. }
  72736. }
  72737. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  72738. /**
  72739. * Get/set the minimum yaw angle that the bone can look to.
  72740. */
  72741. get: function () {
  72742. return this._minYaw;
  72743. },
  72744. set: function (value) {
  72745. this._minYaw = value;
  72746. this._minYawSin = Math.sin(value);
  72747. this._minYawCos = Math.cos(value);
  72748. if (this._maxYaw != null) {
  72749. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  72750. this._yawRange = this._maxYaw - this._minYaw;
  72751. }
  72752. },
  72753. enumerable: true,
  72754. configurable: true
  72755. });
  72756. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  72757. /**
  72758. * Get/set the maximum yaw angle that the bone can look to.
  72759. */
  72760. get: function () {
  72761. return this._maxYaw;
  72762. },
  72763. set: function (value) {
  72764. this._maxYaw = value;
  72765. this._maxYawSin = Math.sin(value);
  72766. this._maxYawCos = Math.cos(value);
  72767. if (this._minYaw != null) {
  72768. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  72769. this._yawRange = this._maxYaw - this._minYaw;
  72770. }
  72771. },
  72772. enumerable: true,
  72773. configurable: true
  72774. });
  72775. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  72776. /**
  72777. * Get/set the minimum pitch angle that the bone can look to.
  72778. */
  72779. get: function () {
  72780. return this._minPitch;
  72781. },
  72782. set: function (value) {
  72783. this._minPitch = value;
  72784. this._minPitchTan = Math.tan(value);
  72785. },
  72786. enumerable: true,
  72787. configurable: true
  72788. });
  72789. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  72790. /**
  72791. * Get/set the maximum pitch angle that the bone can look to.
  72792. */
  72793. get: function () {
  72794. return this._maxPitch;
  72795. },
  72796. set: function (value) {
  72797. this._maxPitch = value;
  72798. this._maxPitchTan = Math.tan(value);
  72799. },
  72800. enumerable: true,
  72801. configurable: true
  72802. });
  72803. /**
  72804. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  72805. */
  72806. BoneLookController.prototype.update = function () {
  72807. //skip the first frame when slerping so that the mesh rotation is correct
  72808. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  72809. this._firstFrameSkipped = true;
  72810. return;
  72811. }
  72812. var bone = this.bone;
  72813. var bonePos = BoneLookController._tmpVecs[0];
  72814. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  72815. var target = this.target;
  72816. var _tmpMat1 = BoneLookController._tmpMats[0];
  72817. var _tmpMat2 = BoneLookController._tmpMats[1];
  72818. var mesh = this.mesh;
  72819. var parentBone = bone.getParent();
  72820. var upAxis = BoneLookController._tmpVecs[1];
  72821. upAxis.copyFrom(this.upAxis);
  72822. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  72823. if (this._transformYawPitch) {
  72824. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  72825. }
  72826. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  72827. }
  72828. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  72829. mesh.getDirectionToRef(upAxis, upAxis);
  72830. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  72831. upAxis.normalize();
  72832. }
  72833. }
  72834. var checkYaw = false;
  72835. var checkPitch = false;
  72836. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  72837. checkYaw = true;
  72838. }
  72839. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  72840. checkPitch = true;
  72841. }
  72842. if (checkYaw || checkPitch) {
  72843. var spaceMat = BoneLookController._tmpMats[2];
  72844. var spaceMatInv = BoneLookController._tmpMats[3];
  72845. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  72846. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  72847. }
  72848. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  72849. spaceMat.copyFrom(mesh.getWorldMatrix());
  72850. }
  72851. else {
  72852. var forwardAxis = BoneLookController._tmpVecs[2];
  72853. forwardAxis.copyFrom(this._fowardAxis);
  72854. if (this._transformYawPitch) {
  72855. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  72856. }
  72857. if (parentBone) {
  72858. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  72859. }
  72860. else {
  72861. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  72862. }
  72863. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  72864. rightAxis.normalize();
  72865. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  72866. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  72867. }
  72868. spaceMat.invertToRef(spaceMatInv);
  72869. var xzlen = null;
  72870. if (checkPitch) {
  72871. var localTarget = BoneLookController._tmpVecs[3];
  72872. target.subtractToRef(bonePos, localTarget);
  72873. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  72874. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  72875. var pitch = Math.atan2(localTarget.y, xzlen);
  72876. var newPitch = pitch;
  72877. if (pitch > this._maxPitch) {
  72878. localTarget.y = this._maxPitchTan * xzlen;
  72879. newPitch = this._maxPitch;
  72880. }
  72881. else if (pitch < this._minPitch) {
  72882. localTarget.y = this._minPitchTan * xzlen;
  72883. newPitch = this._minPitch;
  72884. }
  72885. if (pitch != newPitch) {
  72886. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  72887. localTarget.addInPlace(bonePos);
  72888. target = localTarget;
  72889. }
  72890. }
  72891. if (checkYaw) {
  72892. var localTarget = BoneLookController._tmpVecs[4];
  72893. target.subtractToRef(bonePos, localTarget);
  72894. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  72895. var yaw = Math.atan2(localTarget.x, localTarget.z);
  72896. var newYaw = yaw;
  72897. if (yaw > this._maxYaw || yaw < this._minYaw) {
  72898. if (xzlen == null) {
  72899. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  72900. }
  72901. if (this._yawRange > Math.PI) {
  72902. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  72903. localTarget.z = this._maxYawCos * xzlen;
  72904. localTarget.x = this._maxYawSin * xzlen;
  72905. newYaw = this._maxYaw;
  72906. }
  72907. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  72908. localTarget.z = this._minYawCos * xzlen;
  72909. localTarget.x = this._minYawSin * xzlen;
  72910. newYaw = this._minYaw;
  72911. }
  72912. }
  72913. else {
  72914. if (yaw > this._maxYaw) {
  72915. localTarget.z = this._maxYawCos * xzlen;
  72916. localTarget.x = this._maxYawSin * xzlen;
  72917. newYaw = this._maxYaw;
  72918. }
  72919. else if (yaw < this._minYaw) {
  72920. localTarget.z = this._minYawCos * xzlen;
  72921. localTarget.x = this._minYawSin * xzlen;
  72922. newYaw = this._minYaw;
  72923. }
  72924. }
  72925. }
  72926. if (this._slerping && this._yawRange > Math.PI) {
  72927. //are we going to be crossing into the min/max region?
  72928. var boneFwd = BoneLookController._tmpVecs[8];
  72929. boneFwd.copyFrom(BABYLON.Axis.Z);
  72930. if (this._transformYawPitch) {
  72931. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  72932. }
  72933. var boneRotMat = BoneLookController._tmpMats[4];
  72934. this._boneQuat.toRotationMatrix(boneRotMat);
  72935. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  72936. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  72937. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  72938. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  72939. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  72940. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  72941. if (angBtwTar > angBtwMidYaw) {
  72942. if (xzlen == null) {
  72943. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  72944. }
  72945. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  72946. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  72947. if (angBtwMin < angBtwMax) {
  72948. newYaw = boneYaw + Math.PI * .75;
  72949. localTarget.z = Math.cos(newYaw) * xzlen;
  72950. localTarget.x = Math.sin(newYaw) * xzlen;
  72951. }
  72952. else {
  72953. newYaw = boneYaw - Math.PI * .75;
  72954. localTarget.z = Math.cos(newYaw) * xzlen;
  72955. localTarget.x = Math.sin(newYaw) * xzlen;
  72956. }
  72957. }
  72958. }
  72959. if (yaw != newYaw) {
  72960. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  72961. localTarget.addInPlace(bonePos);
  72962. target = localTarget;
  72963. }
  72964. }
  72965. }
  72966. var zaxis = BoneLookController._tmpVecs[5];
  72967. var xaxis = BoneLookController._tmpVecs[6];
  72968. var yaxis = BoneLookController._tmpVecs[7];
  72969. var _tmpQuat = BoneLookController._tmpQuat;
  72970. target.subtractToRef(bonePos, zaxis);
  72971. zaxis.normalize();
  72972. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  72973. xaxis.normalize();
  72974. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  72975. yaxis.normalize();
  72976. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  72977. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  72978. return;
  72979. }
  72980. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  72981. return;
  72982. }
  72983. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  72984. return;
  72985. }
  72986. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  72987. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  72988. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  72989. }
  72990. if (this.slerpAmount < 1) {
  72991. if (!this._slerping) {
  72992. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  72993. }
  72994. if (this._transformYawPitch) {
  72995. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  72996. }
  72997. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  72998. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  72999. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  73000. this._slerping = true;
  73001. }
  73002. else {
  73003. if (this._transformYawPitch) {
  73004. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  73005. }
  73006. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  73007. this._slerping = false;
  73008. }
  73009. };
  73010. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  73011. var angDiff = ang2 - ang1;
  73012. angDiff %= Math.PI * 2;
  73013. if (angDiff > Math.PI) {
  73014. angDiff -= Math.PI * 2;
  73015. }
  73016. else if (angDiff < -Math.PI) {
  73017. angDiff += Math.PI * 2;
  73018. }
  73019. return angDiff;
  73020. };
  73021. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  73022. ang1 %= (2 * Math.PI);
  73023. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  73024. ang2 %= (2 * Math.PI);
  73025. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  73026. var ab = 0;
  73027. if (ang1 < ang2) {
  73028. ab = ang2 - ang1;
  73029. }
  73030. else {
  73031. ab = ang1 - ang2;
  73032. }
  73033. if (ab > Math.PI) {
  73034. ab = Math.PI * 2 - ab;
  73035. }
  73036. return ab;
  73037. };
  73038. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  73039. ang %= (2 * Math.PI);
  73040. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  73041. ang1 %= (2 * Math.PI);
  73042. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  73043. ang2 %= (2 * Math.PI);
  73044. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  73045. if (ang1 < ang2) {
  73046. if (ang > ang1 && ang < ang2) {
  73047. return true;
  73048. }
  73049. }
  73050. else {
  73051. if (ang > ang2 && ang < ang1) {
  73052. return true;
  73053. }
  73054. }
  73055. return false;
  73056. };
  73057. 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()];
  73058. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  73059. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73060. return BoneLookController;
  73061. }());
  73062. BABYLON.BoneLookController = BoneLookController;
  73063. })(BABYLON || (BABYLON = {}));
  73064. //# sourceMappingURL=babylon.boneLookController.js.map
  73065. "use strict";
  73066. var BABYLON;
  73067. (function (BABYLON) {
  73068. var Skeleton = /** @class */ (function () {
  73069. function Skeleton(name, id, scene) {
  73070. this.name = name;
  73071. this.id = id;
  73072. this.bones = new Array();
  73073. this.needInitialSkinMatrix = false;
  73074. this._isDirty = true;
  73075. this._meshesWithPoseMatrix = new Array();
  73076. this._identity = BABYLON.Matrix.Identity();
  73077. this._ranges = {};
  73078. this._lastAbsoluteTransformsUpdateId = -1;
  73079. /**
  73080. * Specifies if the skeleton should be serialized.
  73081. */
  73082. this.doNotSerialize = false;
  73083. // Events
  73084. /**
  73085. * An event triggered before computing the skeleton's matrices
  73086. * @type {BABYLON.Observable}
  73087. */
  73088. this.onBeforeComputeObservable = new BABYLON.Observable();
  73089. this.bones = [];
  73090. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  73091. scene.skeletons.push(this);
  73092. //make sure it will recalculate the matrix next time prepare is called.
  73093. this._isDirty = true;
  73094. }
  73095. // Members
  73096. Skeleton.prototype.getTransformMatrices = function (mesh) {
  73097. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  73098. return mesh._bonesTransformMatrices;
  73099. }
  73100. if (!this._transformMatrices) {
  73101. this.prepare();
  73102. }
  73103. return this._transformMatrices;
  73104. };
  73105. Skeleton.prototype.getScene = function () {
  73106. return this._scene;
  73107. };
  73108. // Methods
  73109. /**
  73110. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  73111. */
  73112. Skeleton.prototype.toString = function (fullDetails) {
  73113. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  73114. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  73115. if (fullDetails) {
  73116. ret += ", Ranges: {";
  73117. var first = true;
  73118. for (var name_1 in this._ranges) {
  73119. if (first) {
  73120. ret += ", ";
  73121. first = false;
  73122. }
  73123. ret += name_1;
  73124. }
  73125. ret += "}";
  73126. }
  73127. return ret;
  73128. };
  73129. /**
  73130. * Get bone's index searching by name
  73131. * @param {string} name is bone's name to search for
  73132. * @return {number} Indice of the bone. Returns -1 if not found
  73133. */
  73134. Skeleton.prototype.getBoneIndexByName = function (name) {
  73135. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  73136. if (this.bones[boneIndex].name === name) {
  73137. return boneIndex;
  73138. }
  73139. }
  73140. return -1;
  73141. };
  73142. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  73143. // check name not already in use
  73144. if (!this._ranges[name]) {
  73145. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  73146. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73147. if (this.bones[i].animations[0]) {
  73148. this.bones[i].animations[0].createRange(name, from, to);
  73149. }
  73150. }
  73151. }
  73152. };
  73153. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  73154. if (deleteFrames === void 0) { deleteFrames = true; }
  73155. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73156. if (this.bones[i].animations[0]) {
  73157. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  73158. }
  73159. }
  73160. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  73161. };
  73162. Skeleton.prototype.getAnimationRange = function (name) {
  73163. return this._ranges[name];
  73164. };
  73165. /**
  73166. * Returns as an Array, all AnimationRanges defined on this skeleton
  73167. */
  73168. Skeleton.prototype.getAnimationRanges = function () {
  73169. var animationRanges = [];
  73170. var name;
  73171. var i = 0;
  73172. for (name in this._ranges) {
  73173. animationRanges[i] = this._ranges[name];
  73174. i++;
  73175. }
  73176. return animationRanges;
  73177. };
  73178. /**
  73179. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  73180. */
  73181. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  73182. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  73183. if (this._ranges[name] || !source.getAnimationRange(name)) {
  73184. return false;
  73185. }
  73186. var ret = true;
  73187. var frameOffset = this._getHighestAnimationFrame() + 1;
  73188. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  73189. var boneDict = {};
  73190. var sourceBones = source.bones;
  73191. var nBones;
  73192. var i;
  73193. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  73194. boneDict[sourceBones[i].name] = sourceBones[i];
  73195. }
  73196. if (this.bones.length !== sourceBones.length) {
  73197. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  73198. ret = false;
  73199. }
  73200. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  73201. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  73202. var boneName = this.bones[i].name;
  73203. var sourceBone = boneDict[boneName];
  73204. if (sourceBone) {
  73205. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  73206. }
  73207. else {
  73208. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  73209. ret = false;
  73210. }
  73211. }
  73212. // do not call createAnimationRange(), since it also is done to bones, which was already done
  73213. var range = source.getAnimationRange(name);
  73214. if (range) {
  73215. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  73216. }
  73217. return ret;
  73218. };
  73219. Skeleton.prototype.returnToRest = function () {
  73220. for (var index = 0; index < this.bones.length; index++) {
  73221. this.bones[index].returnToRest();
  73222. }
  73223. };
  73224. Skeleton.prototype._getHighestAnimationFrame = function () {
  73225. var ret = 0;
  73226. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73227. if (this.bones[i].animations[0]) {
  73228. var highest = this.bones[i].animations[0].getHighestFrame();
  73229. if (ret < highest) {
  73230. ret = highest;
  73231. }
  73232. }
  73233. }
  73234. return ret;
  73235. };
  73236. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  73237. var range = this.getAnimationRange(name);
  73238. if (!range) {
  73239. return null;
  73240. }
  73241. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  73242. };
  73243. Skeleton.prototype._markAsDirty = function () {
  73244. this._isDirty = true;
  73245. };
  73246. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  73247. this._meshesWithPoseMatrix.push(mesh);
  73248. };
  73249. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  73250. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  73251. if (index > -1) {
  73252. this._meshesWithPoseMatrix.splice(index, 1);
  73253. }
  73254. };
  73255. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  73256. this.onBeforeComputeObservable.notifyObservers(this);
  73257. for (var index = 0; index < this.bones.length; index++) {
  73258. var bone = this.bones[index];
  73259. var parentBone = bone.getParent();
  73260. if (parentBone) {
  73261. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  73262. }
  73263. else {
  73264. if (initialSkinMatrix) {
  73265. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  73266. }
  73267. else {
  73268. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  73269. }
  73270. }
  73271. if (bone._index !== -1) {
  73272. var mappedIndex = bone._index === null ? index : bone._index;
  73273. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  73274. }
  73275. }
  73276. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  73277. };
  73278. Skeleton.prototype.prepare = function () {
  73279. if (!this._isDirty) {
  73280. return;
  73281. }
  73282. if (this.needInitialSkinMatrix) {
  73283. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  73284. var mesh = this._meshesWithPoseMatrix[index];
  73285. var poseMatrix = mesh.getPoseMatrix();
  73286. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  73287. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  73288. }
  73289. if (this._synchronizedWithMesh !== mesh) {
  73290. this._synchronizedWithMesh = mesh;
  73291. // Prepare bones
  73292. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  73293. var bone = this.bones[boneIndex];
  73294. if (!bone.getParent()) {
  73295. var matrix = bone.getBaseMatrix();
  73296. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  73297. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  73298. }
  73299. }
  73300. }
  73301. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  73302. }
  73303. }
  73304. else {
  73305. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  73306. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  73307. }
  73308. this._computeTransformMatrices(this._transformMatrices, null);
  73309. }
  73310. this._isDirty = false;
  73311. this._scene._activeBones.addCount(this.bones.length, false);
  73312. };
  73313. Skeleton.prototype.getAnimatables = function () {
  73314. if (!this._animatables || this._animatables.length !== this.bones.length) {
  73315. this._animatables = [];
  73316. for (var index = 0; index < this.bones.length; index++) {
  73317. this._animatables.push(this.bones[index]);
  73318. }
  73319. }
  73320. return this._animatables;
  73321. };
  73322. Skeleton.prototype.clone = function (name, id) {
  73323. var result = new Skeleton(name, id || name, this._scene);
  73324. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  73325. for (var index = 0; index < this.bones.length; index++) {
  73326. var source = this.bones[index];
  73327. var parentBone = null;
  73328. var parent_1 = source.getParent();
  73329. if (parent_1) {
  73330. var parentIndex = this.bones.indexOf(parent_1);
  73331. parentBone = result.bones[parentIndex];
  73332. }
  73333. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  73334. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  73335. }
  73336. if (this._ranges) {
  73337. result._ranges = {};
  73338. for (var rangeName in this._ranges) {
  73339. var range = this._ranges[rangeName];
  73340. if (range) {
  73341. result._ranges[rangeName] = range.clone();
  73342. }
  73343. }
  73344. }
  73345. this._isDirty = true;
  73346. return result;
  73347. };
  73348. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  73349. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  73350. this.bones.forEach(function (bone) {
  73351. bone.animations.forEach(function (animation) {
  73352. animation.enableBlending = true;
  73353. animation.blendingSpeed = blendingSpeed;
  73354. });
  73355. });
  73356. };
  73357. Skeleton.prototype.dispose = function () {
  73358. this._meshesWithPoseMatrix = [];
  73359. // Animations
  73360. this.getScene().stopAnimation(this);
  73361. // Remove from scene
  73362. this.getScene().removeSkeleton(this);
  73363. };
  73364. Skeleton.prototype.serialize = function () {
  73365. var serializationObject = {};
  73366. serializationObject.name = this.name;
  73367. serializationObject.id = this.id;
  73368. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  73369. serializationObject.bones = [];
  73370. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  73371. for (var index = 0; index < this.bones.length; index++) {
  73372. var bone = this.bones[index];
  73373. var parent_2 = bone.getParent();
  73374. var serializedBone = {
  73375. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  73376. name: bone.name,
  73377. matrix: bone.getBaseMatrix().toArray(),
  73378. rest: bone.getRestPose().toArray()
  73379. };
  73380. serializationObject.bones.push(serializedBone);
  73381. if (bone.length) {
  73382. serializedBone.length = bone.length;
  73383. }
  73384. if (bone.animations && bone.animations.length > 0) {
  73385. serializedBone.animation = bone.animations[0].serialize();
  73386. }
  73387. serializationObject.ranges = [];
  73388. for (var name in this._ranges) {
  73389. var source = this._ranges[name];
  73390. if (!source) {
  73391. continue;
  73392. }
  73393. var range = {};
  73394. range.name = name;
  73395. range.from = source.from;
  73396. range.to = source.to;
  73397. serializationObject.ranges.push(range);
  73398. }
  73399. }
  73400. return serializationObject;
  73401. };
  73402. Skeleton.Parse = function (parsedSkeleton, scene) {
  73403. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  73404. if (parsedSkeleton.dimensionsAtRest) {
  73405. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  73406. }
  73407. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  73408. var index;
  73409. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  73410. var parsedBone = parsedSkeleton.bones[index];
  73411. var parentBone = null;
  73412. if (parsedBone.parentBoneIndex > -1) {
  73413. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  73414. }
  73415. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  73416. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  73417. if (parsedBone.length) {
  73418. bone.length = parsedBone.length;
  73419. }
  73420. if (parsedBone.animation) {
  73421. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  73422. }
  73423. }
  73424. // placed after bones, so createAnimationRange can cascade down
  73425. if (parsedSkeleton.ranges) {
  73426. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  73427. var data = parsedSkeleton.ranges[index];
  73428. skeleton.createAnimationRange(data.name, data.from, data.to);
  73429. }
  73430. }
  73431. return skeleton;
  73432. };
  73433. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  73434. if (forceUpdate === void 0) { forceUpdate = false; }
  73435. var renderId = this._scene.getRenderId();
  73436. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  73437. this.bones[0].computeAbsoluteTransforms();
  73438. this._lastAbsoluteTransformsUpdateId = renderId;
  73439. }
  73440. };
  73441. Skeleton.prototype.getPoseMatrix = function () {
  73442. var poseMatrix = null;
  73443. if (this._meshesWithPoseMatrix.length > 0) {
  73444. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  73445. }
  73446. return poseMatrix;
  73447. };
  73448. Skeleton.prototype.sortBones = function () {
  73449. var bones = new Array();
  73450. var visited = new Array(this.bones.length);
  73451. for (var index = 0; index < this.bones.length; index++) {
  73452. this._sortBones(index, bones, visited);
  73453. }
  73454. this.bones = bones;
  73455. };
  73456. Skeleton.prototype._sortBones = function (index, bones, visited) {
  73457. if (visited[index]) {
  73458. return;
  73459. }
  73460. visited[index] = true;
  73461. var bone = this.bones[index];
  73462. if (bone._index === undefined) {
  73463. bone._index = index;
  73464. }
  73465. var parentBone = bone.getParent();
  73466. if (parentBone) {
  73467. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  73468. }
  73469. bones.push(bone);
  73470. };
  73471. return Skeleton;
  73472. }());
  73473. BABYLON.Skeleton = Skeleton;
  73474. })(BABYLON || (BABYLON = {}));
  73475. //# sourceMappingURL=babylon.skeleton.js.map
  73476. "use strict";
  73477. var BABYLON;
  73478. (function (BABYLON) {
  73479. var SphericalPolynomial = /** @class */ (function () {
  73480. function SphericalPolynomial() {
  73481. this.x = BABYLON.Vector3.Zero();
  73482. this.y = BABYLON.Vector3.Zero();
  73483. this.z = BABYLON.Vector3.Zero();
  73484. this.xx = BABYLON.Vector3.Zero();
  73485. this.yy = BABYLON.Vector3.Zero();
  73486. this.zz = BABYLON.Vector3.Zero();
  73487. this.xy = BABYLON.Vector3.Zero();
  73488. this.yz = BABYLON.Vector3.Zero();
  73489. this.zx = BABYLON.Vector3.Zero();
  73490. }
  73491. SphericalPolynomial.prototype.addAmbient = function (color) {
  73492. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  73493. this.xx = this.xx.add(colorVector);
  73494. this.yy = this.yy.add(colorVector);
  73495. this.zz = this.zz.add(colorVector);
  73496. };
  73497. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  73498. var result = new SphericalPolynomial();
  73499. result.x = harmonics.L11.scale(1.02333);
  73500. result.y = harmonics.L1_1.scale(1.02333);
  73501. result.z = harmonics.L10.scale(1.02333);
  73502. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  73503. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  73504. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  73505. result.yz = harmonics.L2_1.scale(0.858086);
  73506. result.zx = harmonics.L21.scale(0.858086);
  73507. result.xy = harmonics.L2_2.scale(0.858086);
  73508. result.scale(1.0 / Math.PI);
  73509. return result;
  73510. };
  73511. SphericalPolynomial.prototype.scale = function (scale) {
  73512. this.x = this.x.scale(scale);
  73513. this.y = this.y.scale(scale);
  73514. this.z = this.z.scale(scale);
  73515. this.xx = this.xx.scale(scale);
  73516. this.yy = this.yy.scale(scale);
  73517. this.zz = this.zz.scale(scale);
  73518. this.yz = this.yz.scale(scale);
  73519. this.zx = this.zx.scale(scale);
  73520. this.xy = this.xy.scale(scale);
  73521. };
  73522. return SphericalPolynomial;
  73523. }());
  73524. BABYLON.SphericalPolynomial = SphericalPolynomial;
  73525. var SphericalHarmonics = /** @class */ (function () {
  73526. function SphericalHarmonics() {
  73527. this.L00 = BABYLON.Vector3.Zero();
  73528. this.L1_1 = BABYLON.Vector3.Zero();
  73529. this.L10 = BABYLON.Vector3.Zero();
  73530. this.L11 = BABYLON.Vector3.Zero();
  73531. this.L2_2 = BABYLON.Vector3.Zero();
  73532. this.L2_1 = BABYLON.Vector3.Zero();
  73533. this.L20 = BABYLON.Vector3.Zero();
  73534. this.L21 = BABYLON.Vector3.Zero();
  73535. this.L22 = BABYLON.Vector3.Zero();
  73536. }
  73537. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  73538. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  73539. var c = colorVector.scale(deltaSolidAngle);
  73540. this.L00 = this.L00.add(c.scale(0.282095));
  73541. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  73542. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  73543. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  73544. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  73545. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  73546. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  73547. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  73548. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  73549. };
  73550. SphericalHarmonics.prototype.scale = function (scale) {
  73551. this.L00 = this.L00.scale(scale);
  73552. this.L1_1 = this.L1_1.scale(scale);
  73553. this.L10 = this.L10.scale(scale);
  73554. this.L11 = this.L11.scale(scale);
  73555. this.L2_2 = this.L2_2.scale(scale);
  73556. this.L2_1 = this.L2_1.scale(scale);
  73557. this.L20 = this.L20.scale(scale);
  73558. this.L21 = this.L21.scale(scale);
  73559. this.L22 = this.L22.scale(scale);
  73560. };
  73561. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  73562. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  73563. //
  73564. // E_lm = A_l * L_lm
  73565. //
  73566. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  73567. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  73568. // the scaling factors are given in equation 9.
  73569. // Constant (Band 0)
  73570. this.L00 = this.L00.scale(3.141593);
  73571. // Linear (Band 1)
  73572. this.L1_1 = this.L1_1.scale(2.094395);
  73573. this.L10 = this.L10.scale(2.094395);
  73574. this.L11 = this.L11.scale(2.094395);
  73575. // Quadratic (Band 2)
  73576. this.L2_2 = this.L2_2.scale(0.785398);
  73577. this.L2_1 = this.L2_1.scale(0.785398);
  73578. this.L20 = this.L20.scale(0.785398);
  73579. this.L21 = this.L21.scale(0.785398);
  73580. this.L22 = this.L22.scale(0.785398);
  73581. };
  73582. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  73583. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  73584. // L = (1/pi) * E * rho
  73585. //
  73586. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  73587. this.scale(1.0 / Math.PI);
  73588. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  73589. // (The pixel shader must apply albedo after texture fetches, etc).
  73590. };
  73591. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  73592. var result = new SphericalHarmonics();
  73593. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  73594. result.L1_1 = polynomial.y.scale(0.977204);
  73595. result.L10 = polynomial.z.scale(0.977204);
  73596. result.L11 = polynomial.x.scale(0.977204);
  73597. result.L2_2 = polynomial.xy.scale(1.16538);
  73598. result.L2_1 = polynomial.yz.scale(1.16538);
  73599. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  73600. result.L21 = polynomial.zx.scale(1.16538);
  73601. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  73602. result.scale(Math.PI);
  73603. return result;
  73604. };
  73605. return SphericalHarmonics;
  73606. }());
  73607. BABYLON.SphericalHarmonics = SphericalHarmonics;
  73608. })(BABYLON || (BABYLON = {}));
  73609. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  73610. "use strict";
  73611. var BABYLON;
  73612. (function (BABYLON) {
  73613. var FileFaceOrientation = /** @class */ (function () {
  73614. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  73615. this.name = name;
  73616. this.worldAxisForNormal = worldAxisForNormal;
  73617. this.worldAxisForFileX = worldAxisForFileX;
  73618. this.worldAxisForFileY = worldAxisForFileY;
  73619. }
  73620. return FileFaceOrientation;
  73621. }());
  73622. ;
  73623. /**
  73624. * Helper class dealing with the extraction of spherical polynomial dataArray
  73625. * from a cube map.
  73626. */
  73627. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  73628. function CubeMapToSphericalPolynomialTools() {
  73629. }
  73630. /**
  73631. * Converts a texture to the according Spherical Polynomial data.
  73632. * This extracts the first 3 orders only as they are the only one used in the lighting.
  73633. *
  73634. * @param texture The texture to extract the information from.
  73635. * @return The Spherical Polynomial data.
  73636. */
  73637. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  73638. if (!texture.isCube) {
  73639. // Only supports cube Textures currently.
  73640. return null;
  73641. }
  73642. var size = texture.getSize().width;
  73643. var right = texture.readPixels(0);
  73644. var left = texture.readPixels(1);
  73645. var up;
  73646. var down;
  73647. if (texture.isRenderTarget) {
  73648. up = texture.readPixels(3);
  73649. down = texture.readPixels(2);
  73650. }
  73651. else {
  73652. up = texture.readPixels(2);
  73653. down = texture.readPixels(3);
  73654. }
  73655. var front = texture.readPixels(4);
  73656. var back = texture.readPixels(5);
  73657. var gammaSpace = texture.gammaSpace;
  73658. // Always read as RGBA.
  73659. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  73660. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73661. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  73662. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73663. }
  73664. var cubeInfo = {
  73665. size: size,
  73666. right: right,
  73667. left: left,
  73668. up: up,
  73669. down: down,
  73670. front: front,
  73671. back: back,
  73672. format: format,
  73673. type: type,
  73674. gammaSpace: gammaSpace,
  73675. };
  73676. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  73677. };
  73678. /**
  73679. * Converts a cubemap to the according Spherical Polynomial data.
  73680. * This extracts the first 3 orders only as they are the only one used in the lighting.
  73681. *
  73682. * @param cubeInfo The Cube map to extract the information from.
  73683. * @return The Spherical Polynomial data.
  73684. */
  73685. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  73686. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  73687. var totalSolidAngle = 0.0;
  73688. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  73689. var du = 2.0 / cubeInfo.size;
  73690. var dv = du;
  73691. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  73692. var minUV = du * 0.5 - 1.0;
  73693. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  73694. var fileFace = this.FileFaces[faceIndex];
  73695. var dataArray = cubeInfo[fileFace.name];
  73696. var v = minUV;
  73697. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  73698. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  73699. // Because SP is still linear, so summation is fine in that basis.
  73700. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  73701. for (var y = 0; y < cubeInfo.size; y++) {
  73702. var u = minUV;
  73703. for (var x = 0; x < cubeInfo.size; x++) {
  73704. // World direction (not normalised)
  73705. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  73706. worldDirection.normalize();
  73707. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  73708. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  73709. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  73710. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  73711. // Handle Integer types.
  73712. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  73713. r /= 255;
  73714. g /= 255;
  73715. b /= 255;
  73716. }
  73717. // Handle Gamma space textures.
  73718. if (cubeInfo.gammaSpace) {
  73719. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  73720. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  73721. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  73722. }
  73723. var color = new BABYLON.Color3(r, g, b);
  73724. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  73725. totalSolidAngle += deltaSolidAngle;
  73726. u += du;
  73727. }
  73728. v += dv;
  73729. }
  73730. }
  73731. // Solid angle for entire sphere is 4*pi
  73732. var sphereSolidAngle = 4.0 * Math.PI;
  73733. // Adjust the solid angle to allow for how many faces we processed.
  73734. var facesProcessed = 6.0;
  73735. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  73736. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  73737. // This is needed because the numerical integration over the cube uses a
  73738. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  73739. // and also to compensate for accumulative error due to float precision in the summation.
  73740. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  73741. sphericalHarmonics.scale(correctionFactor);
  73742. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  73743. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  73744. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  73745. };
  73746. CubeMapToSphericalPolynomialTools.FileFaces = [
  73747. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  73748. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  73749. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  73750. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  73751. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  73752. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  73753. ];
  73754. return CubeMapToSphericalPolynomialTools;
  73755. }());
  73756. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  73757. })(BABYLON || (BABYLON = {}));
  73758. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  73759. "use strict";
  73760. var BABYLON;
  73761. (function (BABYLON) {
  73762. /**
  73763. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  73764. */
  73765. var PanoramaToCubeMapTools = /** @class */ (function () {
  73766. function PanoramaToCubeMapTools() {
  73767. }
  73768. /**
  73769. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  73770. *
  73771. * @param float32Array The source data.
  73772. * @param inputWidth The width of the input panorama.
  73773. * @param inputhHeight The height of the input panorama.
  73774. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  73775. * @return The cubemap data
  73776. */
  73777. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  73778. if (!float32Array) {
  73779. throw "ConvertPanoramaToCubemap: input cannot be null";
  73780. }
  73781. if (float32Array.length != inputWidth * inputHeight * 3) {
  73782. throw "ConvertPanoramaToCubemap: input size is wrong";
  73783. }
  73784. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  73785. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  73786. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  73787. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  73788. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  73789. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  73790. return {
  73791. front: textureFront,
  73792. back: textureBack,
  73793. left: textureLeft,
  73794. right: textureRight,
  73795. up: textureUp,
  73796. down: textureDown,
  73797. size: size,
  73798. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  73799. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  73800. gammaSpace: false,
  73801. };
  73802. };
  73803. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  73804. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  73805. var textureArray = new Float32Array(buffer);
  73806. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  73807. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  73808. var dy = 1 / texSize;
  73809. var fy = 0;
  73810. for (var y = 0; y < texSize; y++) {
  73811. var xv1 = faceData[0];
  73812. var xv2 = faceData[2];
  73813. for (var x = 0; x < texSize; x++) {
  73814. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  73815. v.normalize();
  73816. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  73817. // 3 channels per pixels
  73818. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  73819. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  73820. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  73821. xv1 = xv1.add(rotDX1);
  73822. xv2 = xv2.add(rotDX2);
  73823. }
  73824. fy += dy;
  73825. }
  73826. return textureArray;
  73827. };
  73828. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  73829. var theta = Math.atan2(vDir.z, vDir.x);
  73830. var phi = Math.acos(vDir.y);
  73831. while (theta < -Math.PI)
  73832. theta += 2 * Math.PI;
  73833. while (theta > Math.PI)
  73834. theta -= 2 * Math.PI;
  73835. var dx = theta / Math.PI;
  73836. var dy = phi / Math.PI;
  73837. // recenter.
  73838. dx = dx * 0.5 + 0.5;
  73839. var px = Math.round(dx * inputWidth);
  73840. if (px < 0)
  73841. px = 0;
  73842. else if (px >= inputWidth)
  73843. px = inputWidth - 1;
  73844. var py = Math.round(dy * inputHeight);
  73845. if (py < 0)
  73846. py = 0;
  73847. else if (py >= inputHeight)
  73848. py = inputHeight - 1;
  73849. var inputY = (inputHeight - py - 1);
  73850. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  73851. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  73852. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  73853. return {
  73854. r: r,
  73855. g: g,
  73856. b: b
  73857. };
  73858. };
  73859. PanoramaToCubeMapTools.FACE_FRONT = [
  73860. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  73861. new BABYLON.Vector3(1.0, -1.0, -1.0),
  73862. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  73863. new BABYLON.Vector3(1.0, 1.0, -1.0)
  73864. ];
  73865. PanoramaToCubeMapTools.FACE_BACK = [
  73866. new BABYLON.Vector3(1.0, -1.0, 1.0),
  73867. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  73868. new BABYLON.Vector3(1.0, 1.0, 1.0),
  73869. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  73870. ];
  73871. PanoramaToCubeMapTools.FACE_RIGHT = [
  73872. new BABYLON.Vector3(1.0, -1.0, -1.0),
  73873. new BABYLON.Vector3(1.0, -1.0, 1.0),
  73874. new BABYLON.Vector3(1.0, 1.0, -1.0),
  73875. new BABYLON.Vector3(1.0, 1.0, 1.0)
  73876. ];
  73877. PanoramaToCubeMapTools.FACE_LEFT = [
  73878. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  73879. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  73880. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  73881. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  73882. ];
  73883. PanoramaToCubeMapTools.FACE_DOWN = [
  73884. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  73885. new BABYLON.Vector3(1.0, 1.0, -1.0),
  73886. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  73887. new BABYLON.Vector3(1.0, 1.0, 1.0)
  73888. ];
  73889. PanoramaToCubeMapTools.FACE_UP = [
  73890. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  73891. new BABYLON.Vector3(1.0, -1.0, 1.0),
  73892. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  73893. new BABYLON.Vector3(1.0, -1.0, -1.0)
  73894. ];
  73895. return PanoramaToCubeMapTools;
  73896. }());
  73897. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  73898. })(BABYLON || (BABYLON = {}));
  73899. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  73900. "use strict";
  73901. var BABYLON;
  73902. (function (BABYLON) {
  73903. ;
  73904. /**
  73905. * This groups tools to convert HDR texture to native colors array.
  73906. */
  73907. var HDRTools = /** @class */ (function () {
  73908. function HDRTools() {
  73909. }
  73910. HDRTools.Ldexp = function (mantissa, exponent) {
  73911. if (exponent > 1023) {
  73912. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  73913. }
  73914. if (exponent < -1074) {
  73915. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  73916. }
  73917. return mantissa * Math.pow(2, exponent);
  73918. };
  73919. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  73920. if (exponent > 0) {
  73921. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  73922. float32array[index + 0] = red * exponent;
  73923. float32array[index + 1] = green * exponent;
  73924. float32array[index + 2] = blue * exponent;
  73925. }
  73926. else {
  73927. float32array[index + 0] = 0;
  73928. float32array[index + 1] = 0;
  73929. float32array[index + 2] = 0;
  73930. }
  73931. };
  73932. HDRTools.readStringLine = function (uint8array, startIndex) {
  73933. var line = "";
  73934. var character = "";
  73935. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  73936. character = String.fromCharCode(uint8array[i]);
  73937. if (character == "\n") {
  73938. break;
  73939. }
  73940. line += character;
  73941. }
  73942. return line;
  73943. };
  73944. /**
  73945. * Reads header information from an RGBE texture stored in a native array.
  73946. * More information on this format are available here:
  73947. * https://en.wikipedia.org/wiki/RGBE_image_format
  73948. *
  73949. * @param uint8array The binary file stored in native array.
  73950. * @return The header information.
  73951. */
  73952. HDRTools.RGBE_ReadHeader = function (uint8array) {
  73953. var height = 0;
  73954. var width = 0;
  73955. var line = this.readStringLine(uint8array, 0);
  73956. if (line[0] != '#' || line[1] != '?') {
  73957. throw "Bad HDR Format.";
  73958. }
  73959. var endOfHeader = false;
  73960. var findFormat = false;
  73961. var lineIndex = 0;
  73962. do {
  73963. lineIndex += (line.length + 1);
  73964. line = this.readStringLine(uint8array, lineIndex);
  73965. if (line == "FORMAT=32-bit_rle_rgbe") {
  73966. findFormat = true;
  73967. }
  73968. else if (line.length == 0) {
  73969. endOfHeader = true;
  73970. }
  73971. } while (!endOfHeader);
  73972. if (!findFormat) {
  73973. throw "HDR Bad header format, unsupported FORMAT";
  73974. }
  73975. lineIndex += (line.length + 1);
  73976. line = this.readStringLine(uint8array, lineIndex);
  73977. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  73978. var match = sizeRegexp.exec(line);
  73979. // TODO. Support +Y and -X if needed.
  73980. if (!match || match.length < 3) {
  73981. throw "HDR Bad header format, no size";
  73982. }
  73983. width = parseInt(match[2]);
  73984. height = parseInt(match[1]);
  73985. if (width < 8 || width > 0x7fff) {
  73986. throw "HDR Bad header format, unsupported size";
  73987. }
  73988. lineIndex += (line.length + 1);
  73989. return {
  73990. height: height,
  73991. width: width,
  73992. dataPosition: lineIndex
  73993. };
  73994. };
  73995. /**
  73996. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  73997. * This RGBE texture needs to store the information as a panorama.
  73998. *
  73999. * More information on this format are available here:
  74000. * https://en.wikipedia.org/wiki/RGBE_image_format
  74001. *
  74002. * @param buffer The binary file stored in an array buffer.
  74003. * @param size The expected size of the extracted cubemap.
  74004. * @return The Cube Map information.
  74005. */
  74006. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  74007. var uint8array = new Uint8Array(buffer);
  74008. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  74009. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  74010. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  74011. return cubeMapData;
  74012. };
  74013. /**
  74014. * Returns the pixels data extracted from an RGBE texture.
  74015. * This pixels will be stored left to right up to down in the R G B order in one array.
  74016. *
  74017. * More information on this format are available here:
  74018. * https://en.wikipedia.org/wiki/RGBE_image_format
  74019. *
  74020. * @param uint8array The binary file stored in an array buffer.
  74021. * @param hdrInfo The header information of the file.
  74022. * @return The pixels data in RGB right to left up to down order.
  74023. */
  74024. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  74025. // Keep for multi format supports.
  74026. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  74027. };
  74028. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  74029. var num_scanlines = hdrInfo.height;
  74030. var scanline_width = hdrInfo.width;
  74031. var a, b, c, d, count;
  74032. var dataIndex = hdrInfo.dataPosition;
  74033. var index = 0, endIndex = 0, i = 0;
  74034. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  74035. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  74036. // 3 channels of 4 bytes per pixel in float.
  74037. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  74038. var resultArray = new Float32Array(resultBuffer);
  74039. // read in each successive scanline
  74040. while (num_scanlines > 0) {
  74041. a = uint8array[dataIndex++];
  74042. b = uint8array[dataIndex++];
  74043. c = uint8array[dataIndex++];
  74044. d = uint8array[dataIndex++];
  74045. if (a != 2 || b != 2 || (c & 0x80)) {
  74046. // this file is not run length encoded
  74047. throw "HDR Bad header format, not RLE";
  74048. }
  74049. if (((c << 8) | d) != scanline_width) {
  74050. throw "HDR Bad header format, wrong scan line width";
  74051. }
  74052. index = 0;
  74053. // read each of the four channels for the scanline into the buffer
  74054. for (i = 0; i < 4; i++) {
  74055. endIndex = (i + 1) * scanline_width;
  74056. while (index < endIndex) {
  74057. a = uint8array[dataIndex++];
  74058. b = uint8array[dataIndex++];
  74059. if (a > 128) {
  74060. // a run of the same value
  74061. count = a - 128;
  74062. if ((count == 0) || (count > endIndex - index)) {
  74063. throw "HDR Bad Format, bad scanline data (run)";
  74064. }
  74065. while (count-- > 0) {
  74066. scanLineArray[index++] = b;
  74067. }
  74068. }
  74069. else {
  74070. // a non-run
  74071. count = a;
  74072. if ((count == 0) || (count > endIndex - index)) {
  74073. throw "HDR Bad Format, bad scanline data (non-run)";
  74074. }
  74075. scanLineArray[index++] = b;
  74076. if (--count > 0) {
  74077. for (var j = 0; j < count; j++) {
  74078. scanLineArray[index++] = uint8array[dataIndex++];
  74079. }
  74080. }
  74081. }
  74082. }
  74083. }
  74084. // now convert data from buffer into floats
  74085. for (i = 0; i < scanline_width; i++) {
  74086. a = scanLineArray[i];
  74087. b = scanLineArray[i + scanline_width];
  74088. c = scanLineArray[i + 2 * scanline_width];
  74089. d = scanLineArray[i + 3 * scanline_width];
  74090. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  74091. }
  74092. num_scanlines--;
  74093. }
  74094. return resultArray;
  74095. };
  74096. return HDRTools;
  74097. }());
  74098. BABYLON.HDRTools = HDRTools;
  74099. })(BABYLON || (BABYLON = {}));
  74100. //# sourceMappingURL=babylon.hdr.js.map
  74101. "use strict";
  74102. var BABYLON;
  74103. (function (BABYLON) {
  74104. /**
  74105. * This represents a texture coming from an HDR input.
  74106. *
  74107. * The only supported format is currently panorama picture stored in RGBE format.
  74108. * Example of such files can be found on HDRLib: http://hdrlib.com/
  74109. */
  74110. var HDRCubeTexture = /** @class */ (function (_super) {
  74111. __extends(HDRCubeTexture, _super);
  74112. /**
  74113. * Instantiates an HDRTexture from the following parameters.
  74114. *
  74115. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  74116. * @param scene The scene the texture will be used in
  74117. * @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.
  74118. * @param noMipmap Forces to not generate the mipmap if true
  74119. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  74120. * @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)
  74121. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  74122. */
  74123. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  74124. if (noMipmap === void 0) { noMipmap = false; }
  74125. if (generateHarmonics === void 0) { generateHarmonics = true; }
  74126. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  74127. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  74128. if (onLoad === void 0) { onLoad = null; }
  74129. if (onError === void 0) { onError = null; }
  74130. var _this = _super.call(this, scene) || this;
  74131. _this._useInGammaSpace = false;
  74132. _this._generateHarmonics = true;
  74133. _this._isBABYLONPreprocessed = false;
  74134. _this._onLoad = null;
  74135. _this._onError = null;
  74136. /**
  74137. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  74138. */
  74139. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  74140. /**
  74141. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  74142. * This is usefull at run time to apply the good shader.
  74143. */
  74144. _this.isPMREM = false;
  74145. _this._isBlocking = true;
  74146. /**
  74147. * Gets or sets the center of the bounding box associated with the cube texture
  74148. * It must define where the camera used to render the texture was set
  74149. */
  74150. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  74151. if (!url) {
  74152. return _this;
  74153. }
  74154. _this.name = url;
  74155. _this.url = url;
  74156. _this.hasAlpha = false;
  74157. _this.isCube = true;
  74158. _this._textureMatrix = BABYLON.Matrix.Identity();
  74159. _this._onLoad = onLoad;
  74160. _this._onError = onError;
  74161. _this.gammaSpace = false;
  74162. var caps = scene.getEngine().getCaps();
  74163. if (size) {
  74164. _this._isBABYLONPreprocessed = false;
  74165. _this._noMipmap = noMipmap;
  74166. _this._size = size;
  74167. _this._useInGammaSpace = useInGammaSpace;
  74168. _this._usePMREMGenerator = usePMREMGenerator &&
  74169. caps.textureLOD &&
  74170. caps.textureFloat &&
  74171. !_this._useInGammaSpace;
  74172. }
  74173. else {
  74174. _this._isBABYLONPreprocessed = true;
  74175. _this._noMipmap = false;
  74176. _this._useInGammaSpace = false;
  74177. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  74178. !_this._useInGammaSpace;
  74179. }
  74180. _this.isPMREM = _this._usePMREMGenerator;
  74181. _this._texture = _this._getFromCache(url, _this._noMipmap);
  74182. if (!_this._texture) {
  74183. if (!scene.useDelayedTextureLoading) {
  74184. _this.loadTexture();
  74185. }
  74186. else {
  74187. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  74188. }
  74189. }
  74190. return _this;
  74191. }
  74192. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  74193. /**
  74194. * Gets wether or not the texture is blocking during loading.
  74195. */
  74196. get: function () {
  74197. return this._isBlocking;
  74198. },
  74199. /**
  74200. * Sets wether or not the texture is blocking during loading.
  74201. */
  74202. set: function (value) {
  74203. this._isBlocking = value;
  74204. },
  74205. enumerable: true,
  74206. configurable: true
  74207. });
  74208. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  74209. get: function () {
  74210. return this._boundingBoxSize;
  74211. },
  74212. /**
  74213. * Gets or sets the size of the bounding box associated with the cube texture
  74214. * When defined, the cubemap will switch to local mode
  74215. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  74216. * @example https://www.babylonjs-playground.com/#RNASML
  74217. */
  74218. set: function (value) {
  74219. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  74220. return;
  74221. }
  74222. this._boundingBoxSize = value;
  74223. var scene = this.getScene();
  74224. if (scene) {
  74225. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  74226. }
  74227. },
  74228. enumerable: true,
  74229. configurable: true
  74230. });
  74231. /**
  74232. * Occurs when the file is a preprocessed .babylon.hdr file.
  74233. */
  74234. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  74235. var _this = this;
  74236. var mipLevels = 0;
  74237. var floatArrayView = null;
  74238. var scene = this.getScene();
  74239. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  74240. var mips = new Array();
  74241. if (!floatArrayView) {
  74242. return mips;
  74243. }
  74244. var startIndex = 30;
  74245. for (var level = 0; level < mipLevels; level++) {
  74246. mips.push([]);
  74247. // Fill each pixel of the mip level.
  74248. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  74249. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74250. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  74251. mips[level].push(faceData);
  74252. startIndex += faceSize;
  74253. }
  74254. }
  74255. return mips;
  74256. } : null;
  74257. var callback = function (buffer) {
  74258. var scene = _this.getScene();
  74259. if (!scene) {
  74260. return null;
  74261. }
  74262. // Create Native Array Views
  74263. var intArrayView = new Int32Array(buffer);
  74264. floatArrayView = new Float32Array(buffer);
  74265. // Fill header.
  74266. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  74267. _this._size = intArrayView[1]; // CubeMap max mip face size.
  74268. // Update Texture Information.
  74269. if (!_this._texture) {
  74270. return null;
  74271. }
  74272. _this._texture.updateSize(_this._size, _this._size);
  74273. // Fill polynomial information.
  74274. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  74275. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  74276. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  74277. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  74278. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  74279. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  74280. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  74281. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  74282. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  74283. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  74284. _this.sphericalPolynomial = sphericalPolynomial;
  74285. // Fill pixel data.
  74286. mipLevels = intArrayView[29]; // Number of mip levels.
  74287. var startIndex = 30;
  74288. var data = [];
  74289. var faceSize = Math.pow(_this._size, 2) * 3;
  74290. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74291. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  74292. startIndex += faceSize;
  74293. }
  74294. var results = [];
  74295. var byteArray = null;
  74296. // Push each faces.
  74297. for (var k = 0; k < 6; k++) {
  74298. var dataFace = null;
  74299. // To be deprecated.
  74300. if (version === 1) {
  74301. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  74302. dataFace = data[j];
  74303. }
  74304. // If special cases.
  74305. if (!mipmapGenerator && dataFace) {
  74306. if (!scene.getEngine().getCaps().textureFloat) {
  74307. // 3 channels of 1 bytes per pixel in bytes.
  74308. var byteBuffer = new ArrayBuffer(faceSize);
  74309. byteArray = new Uint8Array(byteBuffer);
  74310. }
  74311. for (var i = 0; i < _this._size * _this._size; i++) {
  74312. // Put in gamma space if requested.
  74313. if (_this._useInGammaSpace) {
  74314. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  74315. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  74316. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  74317. }
  74318. // Convert to int texture for fallback.
  74319. if (byteArray) {
  74320. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  74321. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  74322. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  74323. // May use luminance instead if the result is not accurate.
  74324. var max = Math.max(Math.max(r, g), b);
  74325. if (max > 255) {
  74326. var scale = 255 / max;
  74327. r *= scale;
  74328. g *= scale;
  74329. b *= scale;
  74330. }
  74331. byteArray[(i * 3) + 0] = r;
  74332. byteArray[(i * 3) + 1] = g;
  74333. byteArray[(i * 3) + 2] = b;
  74334. }
  74335. }
  74336. }
  74337. // Fill the array accordingly.
  74338. if (byteArray) {
  74339. results.push(byteArray);
  74340. }
  74341. else {
  74342. results.push(dataFace);
  74343. }
  74344. }
  74345. return results;
  74346. };
  74347. if (scene) {
  74348. 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);
  74349. }
  74350. };
  74351. /**
  74352. * Occurs when the file is raw .hdr file.
  74353. */
  74354. HDRCubeTexture.prototype.loadHDRTexture = function () {
  74355. var _this = this;
  74356. var callback = function (buffer) {
  74357. var scene = _this.getScene();
  74358. if (!scene) {
  74359. return null;
  74360. }
  74361. // Extract the raw linear data.
  74362. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  74363. // Generate harmonics if needed.
  74364. if (_this._generateHarmonics) {
  74365. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  74366. _this.sphericalPolynomial = sphericalPolynomial;
  74367. }
  74368. var results = [];
  74369. var byteArray = null;
  74370. // Push each faces.
  74371. for (var j = 0; j < 6; j++) {
  74372. // Create uintarray fallback.
  74373. if (!scene.getEngine().getCaps().textureFloat) {
  74374. // 3 channels of 1 bytes per pixel in bytes.
  74375. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  74376. byteArray = new Uint8Array(byteBuffer);
  74377. }
  74378. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  74379. // If special cases.
  74380. if (_this._useInGammaSpace || byteArray) {
  74381. for (var i = 0; i < _this._size * _this._size; i++) {
  74382. // Put in gamma space if requested.
  74383. if (_this._useInGammaSpace) {
  74384. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  74385. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  74386. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  74387. }
  74388. // Convert to int texture for fallback.
  74389. if (byteArray) {
  74390. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  74391. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  74392. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  74393. // May use luminance instead if the result is not accurate.
  74394. var max = Math.max(Math.max(r, g), b);
  74395. if (max > 255) {
  74396. var scale = 255 / max;
  74397. r *= scale;
  74398. g *= scale;
  74399. b *= scale;
  74400. }
  74401. byteArray[(i * 3) + 0] = r;
  74402. byteArray[(i * 3) + 1] = g;
  74403. byteArray[(i * 3) + 2] = b;
  74404. }
  74405. }
  74406. }
  74407. if (byteArray) {
  74408. results.push(byteArray);
  74409. }
  74410. else {
  74411. results.push(dataFace);
  74412. }
  74413. }
  74414. return results;
  74415. };
  74416. var mipmapGenerator = null;
  74417. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  74418. // if (!this._noMipmap &&
  74419. // this._usePMREMGenerator) {
  74420. // mipmapGenerator = (data: ArrayBufferView[]) => {
  74421. // // Custom setup of the generator matching with the PBR shader values.
  74422. // var generator = new BABYLON.PMREMGenerator(data,
  74423. // this._size,
  74424. // this._size,
  74425. // 0,
  74426. // 3,
  74427. // this.getScene().getEngine().getCaps().textureFloat,
  74428. // 2048,
  74429. // 0.25,
  74430. // false,
  74431. // true);
  74432. // return generator.filterCubeMap();
  74433. // };
  74434. // }
  74435. var scene = this.getScene();
  74436. if (scene) {
  74437. 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);
  74438. }
  74439. };
  74440. /**
  74441. * Starts the loading process of the texture.
  74442. */
  74443. HDRCubeTexture.prototype.loadTexture = function () {
  74444. if (this._isBABYLONPreprocessed) {
  74445. this.loadBabylonTexture();
  74446. }
  74447. else {
  74448. this.loadHDRTexture();
  74449. }
  74450. };
  74451. HDRCubeTexture.prototype.clone = function () {
  74452. var scene = this.getScene();
  74453. if (!scene) {
  74454. return this;
  74455. }
  74456. var size = (this._isBABYLONPreprocessed ? null : this._size);
  74457. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  74458. // Base texture
  74459. newTexture.level = this.level;
  74460. newTexture.wrapU = this.wrapU;
  74461. newTexture.wrapV = this.wrapV;
  74462. newTexture.coordinatesIndex = this.coordinatesIndex;
  74463. newTexture.coordinatesMode = this.coordinatesMode;
  74464. return newTexture;
  74465. };
  74466. // Methods
  74467. HDRCubeTexture.prototype.delayLoad = function () {
  74468. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  74469. return;
  74470. }
  74471. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  74472. this._texture = this._getFromCache(this.url, this._noMipmap);
  74473. if (!this._texture) {
  74474. this.loadTexture();
  74475. }
  74476. };
  74477. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  74478. return this._textureMatrix;
  74479. };
  74480. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  74481. this._textureMatrix = value;
  74482. };
  74483. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  74484. var texture = null;
  74485. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  74486. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  74487. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  74488. texture.name = parsedTexture.name;
  74489. texture.hasAlpha = parsedTexture.hasAlpha;
  74490. texture.level = parsedTexture.level;
  74491. texture.coordinatesMode = parsedTexture.coordinatesMode;
  74492. texture.isBlocking = parsedTexture.isBlocking;
  74493. }
  74494. if (texture) {
  74495. if (parsedTexture.boundingBoxPosition) {
  74496. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  74497. }
  74498. if (parsedTexture.boundingBoxSize) {
  74499. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  74500. }
  74501. }
  74502. return texture;
  74503. };
  74504. HDRCubeTexture.prototype.serialize = function () {
  74505. if (!this.name) {
  74506. return null;
  74507. }
  74508. var serializationObject = {};
  74509. serializationObject.name = this.name;
  74510. serializationObject.hasAlpha = this.hasAlpha;
  74511. serializationObject.isCube = true;
  74512. serializationObject.level = this.level;
  74513. serializationObject.size = this._size;
  74514. serializationObject.coordinatesMode = this.coordinatesMode;
  74515. serializationObject.useInGammaSpace = this._useInGammaSpace;
  74516. serializationObject.generateHarmonics = this._generateHarmonics;
  74517. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  74518. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  74519. serializationObject.customType = "BABYLON.HDRCubeTexture";
  74520. serializationObject.noMipmap = this._noMipmap;
  74521. serializationObject.isBlocking = this._isBlocking;
  74522. return serializationObject;
  74523. };
  74524. /**
  74525. * Saves as a file the data contained in the texture in a binary format.
  74526. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  74527. * as the spherical used in the lighting.
  74528. * @param url The HDR file url.
  74529. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  74530. * @param onError Method called if any error happens during download.
  74531. * @return The packed binary data.
  74532. */
  74533. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  74534. if (onError === void 0) { onError = null; }
  74535. var callback = function (buffer) {
  74536. var data = new Blob([buffer], { type: 'application/octet-stream' });
  74537. // Returns a URL you can use as a href.
  74538. var objUrl = window.URL.createObjectURL(data);
  74539. // Simulates a link to it and click to dowload.
  74540. var a = document.createElement("a");
  74541. document.body.appendChild(a);
  74542. a.style.display = "none";
  74543. a.href = objUrl;
  74544. a.download = "envmap.babylon.hdr";
  74545. a.click();
  74546. };
  74547. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  74548. };
  74549. /**
  74550. * Serializes the data contained in the texture in a binary format.
  74551. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  74552. * as the spherical used in the lighting.
  74553. * @param url The HDR file url.
  74554. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  74555. * @param onError Method called if any error happens during download.
  74556. * @return The packed binary data.
  74557. */
  74558. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  74559. if (onError === void 0) { onError = null; }
  74560. // Needs the url tho create the texture.
  74561. if (!url) {
  74562. return;
  74563. }
  74564. // Check Power of two size.
  74565. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  74566. return;
  74567. }
  74568. // Coming Back in 3.x.
  74569. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  74570. };
  74571. HDRCubeTexture._facesMapping = [
  74572. "right",
  74573. "left",
  74574. "up",
  74575. "down",
  74576. "front",
  74577. "back"
  74578. ];
  74579. return HDRCubeTexture;
  74580. }(BABYLON.BaseTexture));
  74581. BABYLON.HDRCubeTexture = HDRCubeTexture;
  74582. })(BABYLON || (BABYLON = {}));
  74583. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  74584. "use strict";
  74585. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  74586. // Huge respect for a such great lib.
  74587. // Earcut license:
  74588. // Copyright (c) 2016, Mapbox
  74589. //
  74590. // Permission to use, copy, modify, and/or distribute this software for any purpose
  74591. // with or without fee is hereby granted, provided that the above copyright notice
  74592. // and this permission notice appear in all copies.
  74593. //
  74594. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  74595. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  74596. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  74597. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  74598. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  74599. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  74600. // THIS SOFTWARE.
  74601. var Earcut;
  74602. (function (Earcut) {
  74603. /**
  74604. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  74605. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  74606. * @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).
  74607. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  74608. */
  74609. function earcut(data, holeIndices, dim) {
  74610. dim = dim || 2;
  74611. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  74612. if (!outerNode)
  74613. return triangles;
  74614. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  74615. if (hasHoles)
  74616. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  74617. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  74618. if (data.length > 80 * dim) {
  74619. minX = maxX = data[0];
  74620. minY = maxY = data[1];
  74621. for (var i = dim; i < outerLen; i += dim) {
  74622. x = data[i];
  74623. y = data[i + 1];
  74624. if (x < minX)
  74625. minX = x;
  74626. if (y < minY)
  74627. minY = y;
  74628. if (x > maxX)
  74629. maxX = x;
  74630. if (y > maxY)
  74631. maxY = y;
  74632. }
  74633. // minX, minY and size are later used to transform coords into integers for z-order calculation
  74634. size = Math.max(maxX - minX, maxY - minY);
  74635. }
  74636. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  74637. return triangles;
  74638. }
  74639. Earcut.earcut = earcut;
  74640. var Node = /** @class */ (function () {
  74641. function Node(i, x, y) {
  74642. this.i = i;
  74643. this.x = x;
  74644. this.y = y;
  74645. this.prev = null;
  74646. this.next = null;
  74647. this.z = null;
  74648. this.prevZ = null;
  74649. this.nextZ = null;
  74650. this.steiner = false;
  74651. }
  74652. return Node;
  74653. }());
  74654. // create a circular doubly linked list from polygon points in the specified winding order
  74655. function linkedList(data, start, end, dim, clockwise) {
  74656. var i, last = null;
  74657. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  74658. for (i = start; i < end; i += dim)
  74659. last = insertNode(i, data[i], data[i + 1], last);
  74660. }
  74661. else {
  74662. for (i = end - dim; i >= start; i -= dim)
  74663. last = insertNode(i, data[i], data[i + 1], last);
  74664. }
  74665. if (last && equals(last, last.next)) {
  74666. removeNode(last);
  74667. last = last.next;
  74668. }
  74669. return last;
  74670. }
  74671. // eliminate colinear or duplicate points
  74672. function filterPoints(start, end) {
  74673. if (!start)
  74674. return start;
  74675. if (!end)
  74676. end = start;
  74677. var p = start, again;
  74678. do {
  74679. again = false;
  74680. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  74681. removeNode(p);
  74682. p = end = p.prev;
  74683. if (p === p.next)
  74684. return undefined;
  74685. again = true;
  74686. }
  74687. else {
  74688. p = p.next;
  74689. }
  74690. } while (again || p !== end);
  74691. return end;
  74692. }
  74693. // main ear slicing loop which triangulates a polygon (given as a linked list)
  74694. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  74695. if (!ear)
  74696. return;
  74697. // interlink polygon nodes in z-order
  74698. if (!pass && size)
  74699. indexCurve(ear, minX, minY, size);
  74700. var stop = ear, prev, next;
  74701. // iterate through ears, slicing them one by one
  74702. while (ear.prev !== ear.next) {
  74703. prev = ear.prev;
  74704. next = ear.next;
  74705. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  74706. // cut off the triangle
  74707. triangles.push(prev.i / dim);
  74708. triangles.push(ear.i / dim);
  74709. triangles.push(next.i / dim);
  74710. removeNode(ear);
  74711. // skipping the next vertice leads to less sliver triangles
  74712. ear = next.next;
  74713. stop = next.next;
  74714. continue;
  74715. }
  74716. ear = next;
  74717. // if we looped through the whole remaining polygon and can't find any more ears
  74718. if (ear === stop) {
  74719. // try filtering points and slicing again
  74720. if (!pass) {
  74721. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  74722. // if this didn't work, try curing all small self-intersections locally
  74723. }
  74724. else if (pass === 1) {
  74725. ear = cureLocalIntersections(ear, triangles, dim);
  74726. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  74727. // as a last resort, try splitting the remaining polygon into two
  74728. }
  74729. else if (pass === 2) {
  74730. splitEarcut(ear, triangles, dim, minX, minY, size);
  74731. }
  74732. break;
  74733. }
  74734. }
  74735. }
  74736. // check whether a polygon node forms a valid ear with adjacent nodes
  74737. function isEar(ear) {
  74738. var a = ear.prev, b = ear, c = ear.next;
  74739. if (area(a, b, c) >= 0)
  74740. return false; // reflex, can't be an ear
  74741. // now make sure we don't have other points inside the potential ear
  74742. var p = ear.next.next;
  74743. while (p !== ear.prev) {
  74744. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  74745. area(p.prev, p, p.next) >= 0)
  74746. return false;
  74747. p = p.next;
  74748. }
  74749. return true;
  74750. }
  74751. function isEarHashed(ear, minX, minY, size) {
  74752. var a = ear.prev, b = ear, c = ear.next;
  74753. if (area(a, b, c) >= 0)
  74754. return false; // reflex, can't be an ear
  74755. // triangle bbox; min & max are calculated like this for speed
  74756. 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);
  74757. // z-order range for the current triangle bbox;
  74758. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  74759. // first look for points inside the triangle in increasing z-order
  74760. var p = ear.nextZ;
  74761. while (p && p.z <= maxZ) {
  74762. if (p !== ear.prev &&
  74763. p !== ear.next &&
  74764. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  74765. area(p.prev, p, p.next) >= 0)
  74766. return false;
  74767. p = p.nextZ;
  74768. }
  74769. // then look for points in decreasing z-order
  74770. p = ear.prevZ;
  74771. while (p && p.z >= minZ) {
  74772. if (p !== ear.prev &&
  74773. p !== ear.next &&
  74774. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  74775. area(p.prev, p, p.next) >= 0)
  74776. return false;
  74777. p = p.prevZ;
  74778. }
  74779. return true;
  74780. }
  74781. // go through all polygon nodes and cure small local self-intersections
  74782. function cureLocalIntersections(start, triangles, dim) {
  74783. var p = start;
  74784. do {
  74785. var a = p.prev, b = p.next.next;
  74786. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  74787. triangles.push(a.i / dim);
  74788. triangles.push(p.i / dim);
  74789. triangles.push(b.i / dim);
  74790. // remove two nodes involved
  74791. removeNode(p);
  74792. removeNode(p.next);
  74793. p = start = b;
  74794. }
  74795. p = p.next;
  74796. } while (p !== start);
  74797. return p;
  74798. }
  74799. // try splitting polygon into two and triangulate them independently
  74800. function splitEarcut(start, triangles, dim, minX, minY, size) {
  74801. // look for a valid diagonal that divides the polygon into two
  74802. var a = start;
  74803. do {
  74804. var b = a.next.next;
  74805. while (b !== a.prev) {
  74806. if (a.i !== b.i && isValidDiagonal(a, b)) {
  74807. // split the polygon in two by the diagonal
  74808. var c = splitPolygon(a, b);
  74809. // filter colinear points around the cuts
  74810. a = filterPoints(a, a.next);
  74811. c = filterPoints(c, c.next);
  74812. // run earcut on each half
  74813. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  74814. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  74815. return;
  74816. }
  74817. b = b.next;
  74818. }
  74819. a = a.next;
  74820. } while (a !== start);
  74821. }
  74822. // link every hole into the outer loop, producing a single-ring polygon without holes
  74823. function eliminateHoles(data, holeIndices, outerNode, dim) {
  74824. var queue = [], i, len, start, end, list;
  74825. for (i = 0, len = holeIndices.length; i < len; i++) {
  74826. start = holeIndices[i] * dim;
  74827. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  74828. list = linkedList(data, start, end, dim, false);
  74829. if (list === list.next)
  74830. list.steiner = true;
  74831. queue.push(getLeftmost(list));
  74832. }
  74833. queue.sort(compareX);
  74834. // process holes from left to right
  74835. for (i = 0; i < queue.length; i++) {
  74836. eliminateHole(queue[i], outerNode);
  74837. outerNode = filterPoints(outerNode, outerNode.next);
  74838. }
  74839. return outerNode;
  74840. }
  74841. function compareX(a, b) {
  74842. return a.x - b.x;
  74843. }
  74844. // find a bridge between vertices that connects hole with an outer ring and and link it
  74845. function eliminateHole(hole, outerNode) {
  74846. outerNode = findHoleBridge(hole, outerNode);
  74847. if (outerNode) {
  74848. var b = splitPolygon(outerNode, hole);
  74849. filterPoints(b, b.next);
  74850. }
  74851. }
  74852. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  74853. function findHoleBridge(hole, outerNode) {
  74854. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  74855. // find a segment intersected by a ray from the hole's leftmost point to the left;
  74856. // segment's endpoint with lesser x will be potential connection point
  74857. do {
  74858. if (hy <= p.y && hy >= p.next.y) {
  74859. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  74860. if (x <= hx && x > qx) {
  74861. qx = x;
  74862. if (x === hx) {
  74863. if (hy === p.y)
  74864. return p;
  74865. if (hy === p.next.y)
  74866. return p.next;
  74867. }
  74868. m = p.x < p.next.x ? p : p.next;
  74869. }
  74870. }
  74871. p = p.next;
  74872. } while (p !== outerNode);
  74873. if (!m)
  74874. return null;
  74875. if (hx === qx)
  74876. return m.prev; // hole touches outer segment; pick lower endpoint
  74877. // look for points inside the triangle of hole point, segment intersection and endpoint;
  74878. // if there are no points found, we have a valid connection;
  74879. // otherwise choose the point of the minimum angle with the ray as connection point
  74880. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  74881. p = m.next;
  74882. while (p !== stop) {
  74883. if (hx >= p.x &&
  74884. p.x >= mx &&
  74885. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  74886. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  74887. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  74888. m = p;
  74889. tanMin = tan;
  74890. }
  74891. }
  74892. p = p.next;
  74893. }
  74894. return m;
  74895. }
  74896. // interlink polygon nodes in z-order
  74897. function indexCurve(start, minX, minY, size) {
  74898. var p = start;
  74899. do {
  74900. if (p.z === null)
  74901. p.z = zOrder(p.x, p.y, minX, minY, size);
  74902. p.prevZ = p.prev;
  74903. p.nextZ = p.next;
  74904. p = p.next;
  74905. } while (p !== start);
  74906. p.prevZ.nextZ = null;
  74907. p.prevZ = null;
  74908. sortLinked(p);
  74909. }
  74910. // Simon Tatham's linked list merge sort algorithm
  74911. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  74912. function sortLinked(list) {
  74913. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  74914. do {
  74915. p = list;
  74916. list = null;
  74917. tail = null;
  74918. numMerges = 0;
  74919. while (p) {
  74920. numMerges++;
  74921. q = p;
  74922. pSize = 0;
  74923. for (i = 0; i < inSize; i++) {
  74924. pSize++;
  74925. q = q.nextZ;
  74926. if (!q)
  74927. break;
  74928. }
  74929. qSize = inSize;
  74930. while (pSize > 0 || (qSize > 0 && q)) {
  74931. if (pSize === 0) {
  74932. e = q;
  74933. q = q.nextZ;
  74934. qSize--;
  74935. }
  74936. else if (qSize === 0 || !q) {
  74937. e = p;
  74938. p = p.nextZ;
  74939. pSize--;
  74940. }
  74941. else if (p.z <= q.z) {
  74942. e = p;
  74943. p = p.nextZ;
  74944. pSize--;
  74945. }
  74946. else {
  74947. e = q;
  74948. q = q.nextZ;
  74949. qSize--;
  74950. }
  74951. if (tail)
  74952. tail.nextZ = e;
  74953. else
  74954. list = e;
  74955. e.prevZ = tail;
  74956. tail = e;
  74957. }
  74958. p = q;
  74959. }
  74960. tail.nextZ = null;
  74961. inSize *= 2;
  74962. } while (numMerges > 1);
  74963. return list;
  74964. }
  74965. // z-order of a point given coords and size of the data bounding box
  74966. function zOrder(x, y, minX, minY, size) {
  74967. // coords are transformed into non-negative 15-bit integer range
  74968. x = 32767 * (x - minX) / size;
  74969. y = 32767 * (y - minY) / size;
  74970. x = (x | (x << 8)) & 0x00FF00FF;
  74971. x = (x | (x << 4)) & 0x0F0F0F0F;
  74972. x = (x | (x << 2)) & 0x33333333;
  74973. x = (x | (x << 1)) & 0x55555555;
  74974. y = (y | (y << 8)) & 0x00FF00FF;
  74975. y = (y | (y << 4)) & 0x0F0F0F0F;
  74976. y = (y | (y << 2)) & 0x33333333;
  74977. y = (y | (y << 1)) & 0x55555555;
  74978. return x | (y << 1);
  74979. }
  74980. // find the leftmost node of a polygon ring
  74981. function getLeftmost(start) {
  74982. var p = start, leftmost = start;
  74983. do {
  74984. if (p.x < leftmost.x)
  74985. leftmost = p;
  74986. p = p.next;
  74987. } while (p !== start);
  74988. return leftmost;
  74989. }
  74990. // check if a point lies within a convex triangle
  74991. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  74992. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  74993. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  74994. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  74995. }
  74996. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  74997. function isValidDiagonal(a, b) {
  74998. return a.next.i !== b.i &&
  74999. a.prev.i !== b.i &&
  75000. !intersectsPolygon(a, b) &&
  75001. locallyInside(a, b) &&
  75002. locallyInside(b, a) &&
  75003. middleInside(a, b);
  75004. }
  75005. // signed area of a triangle
  75006. function area(p, q, r) {
  75007. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  75008. }
  75009. // check if two points are equal
  75010. function equals(p1, p2) {
  75011. return p1.x === p2.x && p1.y === p2.y;
  75012. }
  75013. // check if two segments intersect
  75014. function intersects(p1, q1, p2, q2) {
  75015. if ((equals(p1, q1) && equals(p2, q2)) ||
  75016. (equals(p1, q2) && equals(p2, q1)))
  75017. return true;
  75018. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  75019. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  75020. }
  75021. // check if a polygon diagonal intersects any polygon segments
  75022. function intersectsPolygon(a, b) {
  75023. var p = a;
  75024. do {
  75025. if (p.i !== a.i &&
  75026. p.next.i !== a.i &&
  75027. p.i !== b.i &&
  75028. p.next.i !== b.i &&
  75029. intersects(p, p.next, a, b))
  75030. return true;
  75031. p = p.next;
  75032. } while (p !== a);
  75033. return false;
  75034. }
  75035. // check if a polygon diagonal is locally inside the polygon
  75036. function locallyInside(a, b) {
  75037. return area(a.prev, a, a.next) < 0
  75038. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  75039. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  75040. }
  75041. // check if the middle point of a polygon diagonal is inside the polygon
  75042. function middleInside(a, b) {
  75043. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  75044. do {
  75045. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  75046. inside = !inside;
  75047. p = p.next;
  75048. } while (p !== a);
  75049. return inside;
  75050. }
  75051. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  75052. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  75053. function splitPolygon(a, b) {
  75054. 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;
  75055. a.next = b;
  75056. b.prev = a;
  75057. a2.next = an;
  75058. an.prev = a2;
  75059. b2.next = a2;
  75060. a2.prev = b2;
  75061. bp.next = b2;
  75062. b2.prev = bp;
  75063. return b2;
  75064. }
  75065. // create a node and optionally link it with previous one (in a circular doubly linked list)
  75066. function insertNode(i, x, y, last) {
  75067. var p = new Node(i, x, y);
  75068. if (!last) {
  75069. p.prev = p;
  75070. p.next = p;
  75071. }
  75072. else {
  75073. p.next = last.next;
  75074. p.prev = last;
  75075. last.next.prev = p;
  75076. last.next = p;
  75077. }
  75078. return p;
  75079. }
  75080. function removeNode(p) {
  75081. p.next.prev = p.prev;
  75082. p.prev.next = p.next;
  75083. if (p.prevZ)
  75084. p.prevZ.nextZ = p.nextZ;
  75085. if (p.nextZ)
  75086. p.nextZ.prevZ = p.prevZ;
  75087. }
  75088. /**
  75089. * return a percentage difference between the polygon area and its triangulation area;
  75090. * used to verify correctness of triangulation
  75091. */
  75092. function deviation(data, holeIndices, dim, triangles) {
  75093. var hasHoles = holeIndices && holeIndices.length;
  75094. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  75095. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  75096. if (hasHoles) {
  75097. for (var i = 0, len = holeIndices.length; i < len; i++) {
  75098. var start = holeIndices[i] * dim;
  75099. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  75100. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  75101. }
  75102. }
  75103. var trianglesArea = 0;
  75104. for (i = 0; i < triangles.length; i += 3) {
  75105. var a = triangles[i] * dim;
  75106. var b = triangles[i + 1] * dim;
  75107. var c = triangles[i + 2] * dim;
  75108. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  75109. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  75110. }
  75111. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  75112. }
  75113. Earcut.deviation = deviation;
  75114. ;
  75115. function signedArea(data, start, end, dim) {
  75116. var sum = 0;
  75117. for (var i = start, j = end - dim; i < end; i += dim) {
  75118. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  75119. j = i;
  75120. }
  75121. return sum;
  75122. }
  75123. /**
  75124. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  75125. */
  75126. function flatten(data) {
  75127. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  75128. for (var i = 0; i < data.length; i++) {
  75129. for (var j = 0; j < data[i].length; j++) {
  75130. for (var d = 0; d < dim; d++)
  75131. result.vertices.push(data[i][j][d]);
  75132. }
  75133. if (i > 0) {
  75134. holeIndex += data[i - 1].length;
  75135. result.holes.push(holeIndex);
  75136. }
  75137. }
  75138. return result;
  75139. }
  75140. Earcut.flatten = flatten;
  75141. ;
  75142. })(Earcut || (Earcut = {}));
  75143. //# sourceMappingURL=babylon.earcut.js.map
  75144. "use strict";
  75145. var BABYLON;
  75146. (function (BABYLON) {
  75147. var IndexedVector2 = /** @class */ (function (_super) {
  75148. __extends(IndexedVector2, _super);
  75149. function IndexedVector2(original, index) {
  75150. var _this = _super.call(this, original.x, original.y) || this;
  75151. _this.index = index;
  75152. return _this;
  75153. }
  75154. return IndexedVector2;
  75155. }(BABYLON.Vector2));
  75156. var PolygonPoints = /** @class */ (function () {
  75157. function PolygonPoints() {
  75158. this.elements = new Array();
  75159. }
  75160. PolygonPoints.prototype.add = function (originalPoints) {
  75161. var _this = this;
  75162. var result = new Array();
  75163. originalPoints.forEach(function (point) {
  75164. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  75165. var newPoint = new IndexedVector2(point, _this.elements.length);
  75166. result.push(newPoint);
  75167. _this.elements.push(newPoint);
  75168. }
  75169. });
  75170. return result;
  75171. };
  75172. PolygonPoints.prototype.computeBounds = function () {
  75173. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  75174. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  75175. this.elements.forEach(function (point) {
  75176. // x
  75177. if (point.x < lmin.x) {
  75178. lmin.x = point.x;
  75179. }
  75180. else if (point.x > lmax.x) {
  75181. lmax.x = point.x;
  75182. }
  75183. // y
  75184. if (point.y < lmin.y) {
  75185. lmin.y = point.y;
  75186. }
  75187. else if (point.y > lmax.y) {
  75188. lmax.y = point.y;
  75189. }
  75190. });
  75191. return {
  75192. min: lmin,
  75193. max: lmax,
  75194. width: lmax.x - lmin.x,
  75195. height: lmax.y - lmin.y
  75196. };
  75197. };
  75198. return PolygonPoints;
  75199. }());
  75200. var Polygon = /** @class */ (function () {
  75201. function Polygon() {
  75202. }
  75203. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  75204. return [
  75205. new BABYLON.Vector2(xmin, ymin),
  75206. new BABYLON.Vector2(xmax, ymin),
  75207. new BABYLON.Vector2(xmax, ymax),
  75208. new BABYLON.Vector2(xmin, ymax)
  75209. ];
  75210. };
  75211. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  75212. if (cx === void 0) { cx = 0; }
  75213. if (cy === void 0) { cy = 0; }
  75214. if (numberOfSides === void 0) { numberOfSides = 32; }
  75215. var result = new Array();
  75216. var angle = 0;
  75217. var increment = (Math.PI * 2) / numberOfSides;
  75218. for (var i = 0; i < numberOfSides; i++) {
  75219. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  75220. angle -= increment;
  75221. }
  75222. return result;
  75223. };
  75224. Polygon.Parse = function (input) {
  75225. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  75226. var i, result = [];
  75227. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  75228. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  75229. }
  75230. return result;
  75231. };
  75232. Polygon.StartingAt = function (x, y) {
  75233. return BABYLON.Path2.StartingAt(x, y);
  75234. };
  75235. return Polygon;
  75236. }());
  75237. BABYLON.Polygon = Polygon;
  75238. var PolygonMeshBuilder = /** @class */ (function () {
  75239. function PolygonMeshBuilder(name, contours, scene) {
  75240. this._points = new PolygonPoints();
  75241. this._outlinepoints = new PolygonPoints();
  75242. this._holes = new Array();
  75243. this._epoints = new Array();
  75244. this._eholes = new Array();
  75245. this._name = name;
  75246. this._scene = scene;
  75247. var points;
  75248. if (contours instanceof BABYLON.Path2) {
  75249. points = contours.getPoints();
  75250. }
  75251. else {
  75252. points = contours;
  75253. }
  75254. this._addToepoint(points);
  75255. this._points.add(points);
  75256. this._outlinepoints.add(points);
  75257. }
  75258. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  75259. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  75260. var p = points_1[_i];
  75261. this._epoints.push(p.x, p.y);
  75262. }
  75263. };
  75264. PolygonMeshBuilder.prototype.addHole = function (hole) {
  75265. this._points.add(hole);
  75266. var holepoints = new PolygonPoints();
  75267. holepoints.add(hole);
  75268. this._holes.push(holepoints);
  75269. this._eholes.push(this._epoints.length / 2);
  75270. this._addToepoint(hole);
  75271. return this;
  75272. };
  75273. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  75274. var _this = this;
  75275. if (updatable === void 0) { updatable = false; }
  75276. if (depth === void 0) { depth = 0; }
  75277. var result = new BABYLON.Mesh(this._name, this._scene);
  75278. var normals = new Array();
  75279. var positions = new Array();
  75280. var uvs = new Array();
  75281. var bounds = this._points.computeBounds();
  75282. this._points.elements.forEach(function (p) {
  75283. normals.push(0, 1.0, 0);
  75284. positions.push(p.x, 0, p.y);
  75285. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  75286. });
  75287. var indices = new Array();
  75288. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  75289. for (var i = 0; i < res.length; i++) {
  75290. indices.push(res[i]);
  75291. }
  75292. if (depth > 0) {
  75293. var positionscount = (positions.length / 3); //get the current pointcount
  75294. this._points.elements.forEach(function (p) {
  75295. normals.push(0, -1.0, 0);
  75296. positions.push(p.x, -depth, p.y);
  75297. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  75298. });
  75299. var totalCount = indices.length;
  75300. for (var i = 0; i < totalCount; i += 3) {
  75301. var i0 = indices[i + 0];
  75302. var i1 = indices[i + 1];
  75303. var i2 = indices[i + 2];
  75304. indices.push(i2 + positionscount);
  75305. indices.push(i1 + positionscount);
  75306. indices.push(i0 + positionscount);
  75307. }
  75308. //Add the sides
  75309. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  75310. this._holes.forEach(function (hole) {
  75311. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  75312. });
  75313. }
  75314. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  75315. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  75316. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  75317. result.setIndices(indices);
  75318. return result;
  75319. };
  75320. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  75321. var StartIndex = positions.length / 3;
  75322. var ulength = 0;
  75323. for (var i = 0; i < points.elements.length; i++) {
  75324. var p = points.elements[i];
  75325. var p1;
  75326. if ((i + 1) > points.elements.length - 1) {
  75327. p1 = points.elements[0];
  75328. }
  75329. else {
  75330. p1 = points.elements[i + 1];
  75331. }
  75332. positions.push(p.x, 0, p.y);
  75333. positions.push(p.x, -depth, p.y);
  75334. positions.push(p1.x, 0, p1.y);
  75335. positions.push(p1.x, -depth, p1.y);
  75336. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  75337. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  75338. var v3 = v2.subtract(v1);
  75339. var v4 = new BABYLON.Vector3(0, 1, 0);
  75340. var vn = BABYLON.Vector3.Cross(v3, v4);
  75341. vn = vn.normalize();
  75342. uvs.push(ulength / bounds.width, 0);
  75343. uvs.push(ulength / bounds.width, 1);
  75344. ulength += v3.length();
  75345. uvs.push((ulength / bounds.width), 0);
  75346. uvs.push((ulength / bounds.width), 1);
  75347. if (!flip) {
  75348. normals.push(-vn.x, -vn.y, -vn.z);
  75349. normals.push(-vn.x, -vn.y, -vn.z);
  75350. normals.push(-vn.x, -vn.y, -vn.z);
  75351. normals.push(-vn.x, -vn.y, -vn.z);
  75352. indices.push(StartIndex);
  75353. indices.push(StartIndex + 1);
  75354. indices.push(StartIndex + 2);
  75355. indices.push(StartIndex + 1);
  75356. indices.push(StartIndex + 3);
  75357. indices.push(StartIndex + 2);
  75358. }
  75359. else {
  75360. normals.push(vn.x, vn.y, vn.z);
  75361. normals.push(vn.x, vn.y, vn.z);
  75362. normals.push(vn.x, vn.y, vn.z);
  75363. normals.push(vn.x, vn.y, vn.z);
  75364. indices.push(StartIndex);
  75365. indices.push(StartIndex + 2);
  75366. indices.push(StartIndex + 1);
  75367. indices.push(StartIndex + 1);
  75368. indices.push(StartIndex + 2);
  75369. indices.push(StartIndex + 3);
  75370. }
  75371. StartIndex += 4;
  75372. }
  75373. ;
  75374. };
  75375. return PolygonMeshBuilder;
  75376. }());
  75377. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  75378. })(BABYLON || (BABYLON = {}));
  75379. //# sourceMappingURL=babylon.polygonMesh.js.map
  75380. "use strict";
  75381. var BABYLON;
  75382. (function (BABYLON) {
  75383. // Unique ID when we import meshes from Babylon to CSG
  75384. var currentCSGMeshId = 0;
  75385. // # class Vertex
  75386. // Represents a vertex of a polygon. Use your own vertex class instead of this
  75387. // one to provide additional features like texture coordinates and vertex
  75388. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  75389. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  75390. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  75391. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  75392. // is not used anywhere else.
  75393. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  75394. var Vertex = /** @class */ (function () {
  75395. function Vertex(pos, normal, uv) {
  75396. this.pos = pos;
  75397. this.normal = normal;
  75398. this.uv = uv;
  75399. }
  75400. Vertex.prototype.clone = function () {
  75401. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  75402. };
  75403. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  75404. // orientation of a polygon is flipped.
  75405. Vertex.prototype.flip = function () {
  75406. this.normal = this.normal.scale(-1);
  75407. };
  75408. // Create a new vertex between this vertex and `other` by linearly
  75409. // interpolating all properties using a parameter of `t`. Subclasses should
  75410. // override this to interpolate additional properties.
  75411. Vertex.prototype.interpolate = function (other, t) {
  75412. 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));
  75413. };
  75414. return Vertex;
  75415. }());
  75416. // # class Plane
  75417. // Represents a plane in 3D space.
  75418. var Plane = /** @class */ (function () {
  75419. function Plane(normal, w) {
  75420. this.normal = normal;
  75421. this.w = w;
  75422. }
  75423. Plane.FromPoints = function (a, b, c) {
  75424. var v0 = c.subtract(a);
  75425. var v1 = b.subtract(a);
  75426. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  75427. return null;
  75428. }
  75429. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  75430. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  75431. };
  75432. Plane.prototype.clone = function () {
  75433. return new Plane(this.normal.clone(), this.w);
  75434. };
  75435. Plane.prototype.flip = function () {
  75436. this.normal.scaleInPlace(-1);
  75437. this.w = -this.w;
  75438. };
  75439. // Split `polygon` by this plane if needed, then put the polygon or polygon
  75440. // fragments in the appropriate lists. Coplanar polygons go into either
  75441. // `coplanarFront` or `coplanarBack` depending on their orientation with
  75442. // respect to this plane. Polygons in front or in back of this plane go into
  75443. // either `front` or `back`.
  75444. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  75445. var COPLANAR = 0;
  75446. var FRONT = 1;
  75447. var BACK = 2;
  75448. var SPANNING = 3;
  75449. // Classify each point as well as the entire polygon into one of the above
  75450. // four classes.
  75451. var polygonType = 0;
  75452. var types = [];
  75453. var i;
  75454. var t;
  75455. for (i = 0; i < polygon.vertices.length; i++) {
  75456. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  75457. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  75458. polygonType |= type;
  75459. types.push(type);
  75460. }
  75461. // Put the polygon in the correct list, splitting it when necessary.
  75462. switch (polygonType) {
  75463. case COPLANAR:
  75464. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  75465. break;
  75466. case FRONT:
  75467. front.push(polygon);
  75468. break;
  75469. case BACK:
  75470. back.push(polygon);
  75471. break;
  75472. case SPANNING:
  75473. var f = [], b = [];
  75474. for (i = 0; i < polygon.vertices.length; i++) {
  75475. var j = (i + 1) % polygon.vertices.length;
  75476. var ti = types[i], tj = types[j];
  75477. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  75478. if (ti !== BACK)
  75479. f.push(vi);
  75480. if (ti !== FRONT)
  75481. b.push(ti !== BACK ? vi.clone() : vi);
  75482. if ((ti | tj) === SPANNING) {
  75483. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  75484. var v = vi.interpolate(vj, t);
  75485. f.push(v);
  75486. b.push(v.clone());
  75487. }
  75488. }
  75489. var poly;
  75490. if (f.length >= 3) {
  75491. poly = new Polygon(f, polygon.shared);
  75492. if (poly.plane)
  75493. front.push(poly);
  75494. }
  75495. if (b.length >= 3) {
  75496. poly = new Polygon(b, polygon.shared);
  75497. if (poly.plane)
  75498. back.push(poly);
  75499. }
  75500. break;
  75501. }
  75502. };
  75503. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  75504. // point is on the plane.
  75505. Plane.EPSILON = 1e-5;
  75506. return Plane;
  75507. }());
  75508. // # class Polygon
  75509. // Represents a convex polygon. The vertices used to initialize a polygon must
  75510. // be coplanar and form a convex loop.
  75511. //
  75512. // Each convex polygon has a `shared` property, which is shared between all
  75513. // polygons that are clones of each other or were split from the same polygon.
  75514. // This can be used to define per-polygon properties (such as surface color).
  75515. var Polygon = /** @class */ (function () {
  75516. function Polygon(vertices, shared) {
  75517. this.vertices = vertices;
  75518. this.shared = shared;
  75519. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  75520. }
  75521. Polygon.prototype.clone = function () {
  75522. var vertices = this.vertices.map(function (v) { return v.clone(); });
  75523. return new Polygon(vertices, this.shared);
  75524. };
  75525. Polygon.prototype.flip = function () {
  75526. this.vertices.reverse().map(function (v) { v.flip(); });
  75527. this.plane.flip();
  75528. };
  75529. return Polygon;
  75530. }());
  75531. // # class Node
  75532. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  75533. // by picking a polygon to split along. That polygon (and all other coplanar
  75534. // polygons) are added directly to that node and the other polygons are added to
  75535. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  75536. // no distinction between internal and leaf nodes.
  75537. var Node = /** @class */ (function () {
  75538. function Node(polygons) {
  75539. this.plane = null;
  75540. this.front = null;
  75541. this.back = null;
  75542. this.polygons = new Array();
  75543. if (polygons) {
  75544. this.build(polygons);
  75545. }
  75546. }
  75547. Node.prototype.clone = function () {
  75548. var node = new Node();
  75549. node.plane = this.plane && this.plane.clone();
  75550. node.front = this.front && this.front.clone();
  75551. node.back = this.back && this.back.clone();
  75552. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  75553. return node;
  75554. };
  75555. // Convert solid space to empty space and empty space to solid space.
  75556. Node.prototype.invert = function () {
  75557. for (var i = 0; i < this.polygons.length; i++) {
  75558. this.polygons[i].flip();
  75559. }
  75560. if (this.plane) {
  75561. this.plane.flip();
  75562. }
  75563. if (this.front) {
  75564. this.front.invert();
  75565. }
  75566. if (this.back) {
  75567. this.back.invert();
  75568. }
  75569. var temp = this.front;
  75570. this.front = this.back;
  75571. this.back = temp;
  75572. };
  75573. // Recursively remove all polygons in `polygons` that are inside this BSP
  75574. // tree.
  75575. Node.prototype.clipPolygons = function (polygons) {
  75576. if (!this.plane)
  75577. return polygons.slice();
  75578. var front = new Array(), back = new Array();
  75579. for (var i = 0; i < polygons.length; i++) {
  75580. this.plane.splitPolygon(polygons[i], front, back, front, back);
  75581. }
  75582. if (this.front) {
  75583. front = this.front.clipPolygons(front);
  75584. }
  75585. if (this.back) {
  75586. back = this.back.clipPolygons(back);
  75587. }
  75588. else {
  75589. back = [];
  75590. }
  75591. return front.concat(back);
  75592. };
  75593. // Remove all polygons in this BSP tree that are inside the other BSP tree
  75594. // `bsp`.
  75595. Node.prototype.clipTo = function (bsp) {
  75596. this.polygons = bsp.clipPolygons(this.polygons);
  75597. if (this.front)
  75598. this.front.clipTo(bsp);
  75599. if (this.back)
  75600. this.back.clipTo(bsp);
  75601. };
  75602. // Return a list of all polygons in this BSP tree.
  75603. Node.prototype.allPolygons = function () {
  75604. var polygons = this.polygons.slice();
  75605. if (this.front)
  75606. polygons = polygons.concat(this.front.allPolygons());
  75607. if (this.back)
  75608. polygons = polygons.concat(this.back.allPolygons());
  75609. return polygons;
  75610. };
  75611. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  75612. // new polygons are filtered down to the bottom of the tree and become new
  75613. // nodes there. Each set of polygons is partitioned using the first polygon
  75614. // (no heuristic is used to pick a good split).
  75615. Node.prototype.build = function (polygons) {
  75616. if (!polygons.length)
  75617. return;
  75618. if (!this.plane)
  75619. this.plane = polygons[0].plane.clone();
  75620. var front = new Array(), back = new Array();
  75621. for (var i = 0; i < polygons.length; i++) {
  75622. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  75623. }
  75624. if (front.length) {
  75625. if (!this.front)
  75626. this.front = new Node();
  75627. this.front.build(front);
  75628. }
  75629. if (back.length) {
  75630. if (!this.back)
  75631. this.back = new Node();
  75632. this.back.build(back);
  75633. }
  75634. };
  75635. return Node;
  75636. }());
  75637. var CSG = /** @class */ (function () {
  75638. function CSG() {
  75639. this.polygons = new Array();
  75640. }
  75641. // Convert BABYLON.Mesh to BABYLON.CSG
  75642. CSG.FromMesh = function (mesh) {
  75643. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  75644. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  75645. if (mesh instanceof BABYLON.Mesh) {
  75646. mesh.computeWorldMatrix(true);
  75647. matrix = mesh.getWorldMatrix();
  75648. meshPosition = mesh.position.clone();
  75649. meshRotation = mesh.rotation.clone();
  75650. if (mesh.rotationQuaternion) {
  75651. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  75652. }
  75653. meshScaling = mesh.scaling.clone();
  75654. }
  75655. else {
  75656. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  75657. }
  75658. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  75659. var subMeshes = mesh.subMeshes;
  75660. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  75661. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  75662. vertices = [];
  75663. for (var j = 0; j < 3; j++) {
  75664. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  75665. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  75666. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  75667. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  75668. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  75669. vertex = new Vertex(position, normal, uv);
  75670. vertices.push(vertex);
  75671. }
  75672. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  75673. // To handle the case of degenerated triangle
  75674. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  75675. if (polygon.plane)
  75676. polygons.push(polygon);
  75677. }
  75678. }
  75679. var csg = CSG.FromPolygons(polygons);
  75680. csg.matrix = matrix;
  75681. csg.position = meshPosition;
  75682. csg.rotation = meshRotation;
  75683. csg.scaling = meshScaling;
  75684. csg.rotationQuaternion = meshRotationQuaternion;
  75685. currentCSGMeshId++;
  75686. return csg;
  75687. };
  75688. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  75689. CSG.FromPolygons = function (polygons) {
  75690. var csg = new CSG();
  75691. csg.polygons = polygons;
  75692. return csg;
  75693. };
  75694. CSG.prototype.clone = function () {
  75695. var csg = new CSG();
  75696. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  75697. csg.copyTransformAttributes(this);
  75698. return csg;
  75699. };
  75700. CSG.prototype.union = function (csg) {
  75701. var a = new Node(this.clone().polygons);
  75702. var b = new Node(csg.clone().polygons);
  75703. a.clipTo(b);
  75704. b.clipTo(a);
  75705. b.invert();
  75706. b.clipTo(a);
  75707. b.invert();
  75708. a.build(b.allPolygons());
  75709. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  75710. };
  75711. CSG.prototype.unionInPlace = function (csg) {
  75712. var a = new Node(this.polygons);
  75713. var b = new Node(csg.polygons);
  75714. a.clipTo(b);
  75715. b.clipTo(a);
  75716. b.invert();
  75717. b.clipTo(a);
  75718. b.invert();
  75719. a.build(b.allPolygons());
  75720. this.polygons = a.allPolygons();
  75721. };
  75722. CSG.prototype.subtract = function (csg) {
  75723. var a = new Node(this.clone().polygons);
  75724. var b = new Node(csg.clone().polygons);
  75725. a.invert();
  75726. a.clipTo(b);
  75727. b.clipTo(a);
  75728. b.invert();
  75729. b.clipTo(a);
  75730. b.invert();
  75731. a.build(b.allPolygons());
  75732. a.invert();
  75733. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  75734. };
  75735. CSG.prototype.subtractInPlace = function (csg) {
  75736. var a = new Node(this.polygons);
  75737. var b = new Node(csg.polygons);
  75738. a.invert();
  75739. a.clipTo(b);
  75740. b.clipTo(a);
  75741. b.invert();
  75742. b.clipTo(a);
  75743. b.invert();
  75744. a.build(b.allPolygons());
  75745. a.invert();
  75746. this.polygons = a.allPolygons();
  75747. };
  75748. CSG.prototype.intersect = function (csg) {
  75749. var a = new Node(this.clone().polygons);
  75750. var b = new Node(csg.clone().polygons);
  75751. a.invert();
  75752. b.clipTo(a);
  75753. b.invert();
  75754. a.clipTo(b);
  75755. b.clipTo(a);
  75756. a.build(b.allPolygons());
  75757. a.invert();
  75758. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  75759. };
  75760. CSG.prototype.intersectInPlace = function (csg) {
  75761. var a = new Node(this.polygons);
  75762. var b = new Node(csg.polygons);
  75763. a.invert();
  75764. b.clipTo(a);
  75765. b.invert();
  75766. a.clipTo(b);
  75767. b.clipTo(a);
  75768. a.build(b.allPolygons());
  75769. a.invert();
  75770. this.polygons = a.allPolygons();
  75771. };
  75772. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  75773. // not modified.
  75774. CSG.prototype.inverse = function () {
  75775. var csg = this.clone();
  75776. csg.inverseInPlace();
  75777. return csg;
  75778. };
  75779. CSG.prototype.inverseInPlace = function () {
  75780. this.polygons.map(function (p) { p.flip(); });
  75781. };
  75782. // This is used to keep meshes transformations so they can be restored
  75783. // when we build back a Babylon Mesh
  75784. // NB : All CSG operations are performed in world coordinates
  75785. CSG.prototype.copyTransformAttributes = function (csg) {
  75786. this.matrix = csg.matrix;
  75787. this.position = csg.position;
  75788. this.rotation = csg.rotation;
  75789. this.scaling = csg.scaling;
  75790. this.rotationQuaternion = csg.rotationQuaternion;
  75791. return this;
  75792. };
  75793. // Build Raw mesh from CSG
  75794. // Coordinates here are in world space
  75795. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  75796. var matrix = this.matrix.clone();
  75797. matrix.invert();
  75798. 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;
  75799. if (keepSubMeshes) {
  75800. // Sort Polygons, since subMeshes are indices range
  75801. polygons.sort(function (a, b) {
  75802. if (a.shared.meshId === b.shared.meshId) {
  75803. return a.shared.subMeshId - b.shared.subMeshId;
  75804. }
  75805. else {
  75806. return a.shared.meshId - b.shared.meshId;
  75807. }
  75808. });
  75809. }
  75810. for (var i = 0, il = polygons.length; i < il; i++) {
  75811. polygon = polygons[i];
  75812. // Building SubMeshes
  75813. if (!subMesh_dict[polygon.shared.meshId]) {
  75814. subMesh_dict[polygon.shared.meshId] = {};
  75815. }
  75816. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  75817. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  75818. indexStart: +Infinity,
  75819. indexEnd: -Infinity,
  75820. materialIndex: polygon.shared.materialIndex
  75821. };
  75822. }
  75823. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  75824. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  75825. polygonIndices[0] = 0;
  75826. polygonIndices[1] = j - 1;
  75827. polygonIndices[2] = j;
  75828. for (var k = 0; k < 3; k++) {
  75829. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  75830. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  75831. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  75832. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  75833. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  75834. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  75835. // Check if 2 points can be merged
  75836. if (!(typeof vertex_idx !== 'undefined' &&
  75837. normals[vertex_idx * 3] === localNormal.x &&
  75838. normals[vertex_idx * 3 + 1] === localNormal.y &&
  75839. normals[vertex_idx * 3 + 2] === localNormal.z &&
  75840. uvs[vertex_idx * 2] === uv.x &&
  75841. uvs[vertex_idx * 2 + 1] === uv.y)) {
  75842. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  75843. uvs.push(uv.x, uv.y);
  75844. normals.push(normal.x, normal.y, normal.z);
  75845. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  75846. }
  75847. indices.push(vertex_idx);
  75848. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  75849. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  75850. currentIndex++;
  75851. }
  75852. }
  75853. }
  75854. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  75855. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  75856. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  75857. mesh.setIndices(indices, null);
  75858. if (keepSubMeshes) {
  75859. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  75860. var materialIndexOffset = 0, materialMaxIndex;
  75861. mesh.subMeshes = new Array();
  75862. for (var m in subMesh_dict) {
  75863. materialMaxIndex = -1;
  75864. for (var sm in subMesh_dict[m]) {
  75865. subMesh_obj = subMesh_dict[m][sm];
  75866. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  75867. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  75868. }
  75869. materialIndexOffset += ++materialMaxIndex;
  75870. }
  75871. }
  75872. return mesh;
  75873. };
  75874. // Build Mesh from CSG taking material and transforms into account
  75875. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  75876. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  75877. mesh.material = material;
  75878. mesh.position.copyFrom(this.position);
  75879. mesh.rotation.copyFrom(this.rotation);
  75880. if (this.rotationQuaternion) {
  75881. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  75882. }
  75883. mesh.scaling.copyFrom(this.scaling);
  75884. mesh.computeWorldMatrix(true);
  75885. return mesh;
  75886. };
  75887. return CSG;
  75888. }());
  75889. BABYLON.CSG = CSG;
  75890. })(BABYLON || (BABYLON = {}));
  75891. //# sourceMappingURL=babylon.csg.js.map
  75892. "use strict";
  75893. var BABYLON;
  75894. (function (BABYLON) {
  75895. var LensFlare = /** @class */ (function () {
  75896. function LensFlare(size, position, color, imgUrl, system) {
  75897. this.size = size;
  75898. this.position = position;
  75899. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  75900. this.color = color || new BABYLON.Color3(1, 1, 1);
  75901. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  75902. this._system = system;
  75903. system.lensFlares.push(this);
  75904. }
  75905. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  75906. return new LensFlare(size, position, color, imgUrl, system);
  75907. };
  75908. LensFlare.prototype.dispose = function () {
  75909. if (this.texture) {
  75910. this.texture.dispose();
  75911. }
  75912. // Remove from scene
  75913. var index = this._system.lensFlares.indexOf(this);
  75914. this._system.lensFlares.splice(index, 1);
  75915. };
  75916. ;
  75917. return LensFlare;
  75918. }());
  75919. BABYLON.LensFlare = LensFlare;
  75920. })(BABYLON || (BABYLON = {}));
  75921. //# sourceMappingURL=babylon.lensFlare.js.map
  75922. "use strict";
  75923. var BABYLON;
  75924. (function (BABYLON) {
  75925. var LensFlareSystem = /** @class */ (function () {
  75926. function LensFlareSystem(name, emitter, scene) {
  75927. this.name = name;
  75928. this.lensFlares = new Array();
  75929. this.borderLimit = 300;
  75930. this.viewportBorder = 0;
  75931. this.layerMask = 0x0FFFFFFF;
  75932. this._vertexBuffers = {};
  75933. this._isEnabled = true;
  75934. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  75935. this._emitter = emitter;
  75936. this.id = name;
  75937. scene.lensFlareSystems.push(this);
  75938. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  75939. var engine = scene.getEngine();
  75940. // VBO
  75941. var vertices = [];
  75942. vertices.push(1, 1);
  75943. vertices.push(-1, 1);
  75944. vertices.push(-1, -1);
  75945. vertices.push(1, -1);
  75946. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  75947. // Indices
  75948. var indices = [];
  75949. indices.push(0);
  75950. indices.push(1);
  75951. indices.push(2);
  75952. indices.push(0);
  75953. indices.push(2);
  75954. indices.push(3);
  75955. this._indexBuffer = engine.createIndexBuffer(indices);
  75956. // Effects
  75957. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  75958. }
  75959. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  75960. get: function () {
  75961. return this._isEnabled;
  75962. },
  75963. set: function (value) {
  75964. this._isEnabled = value;
  75965. },
  75966. enumerable: true,
  75967. configurable: true
  75968. });
  75969. LensFlareSystem.prototype.getScene = function () {
  75970. return this._scene;
  75971. };
  75972. LensFlareSystem.prototype.getEmitter = function () {
  75973. return this._emitter;
  75974. };
  75975. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  75976. this._emitter = newEmitter;
  75977. };
  75978. LensFlareSystem.prototype.getEmitterPosition = function () {
  75979. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  75980. };
  75981. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  75982. var position = this.getEmitterPosition();
  75983. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  75984. this._positionX = position.x;
  75985. this._positionY = position.y;
  75986. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  75987. if (this.viewportBorder > 0) {
  75988. globalViewport.x -= this.viewportBorder;
  75989. globalViewport.y -= this.viewportBorder;
  75990. globalViewport.width += this.viewportBorder * 2;
  75991. globalViewport.height += this.viewportBorder * 2;
  75992. position.x += this.viewportBorder;
  75993. position.y += this.viewportBorder;
  75994. this._positionX += this.viewportBorder;
  75995. this._positionY += this.viewportBorder;
  75996. }
  75997. if (position.z > 0) {
  75998. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  75999. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  76000. return true;
  76001. }
  76002. return true;
  76003. }
  76004. return false;
  76005. };
  76006. LensFlareSystem.prototype._isVisible = function () {
  76007. if (!this._isEnabled || !this._scene.activeCamera) {
  76008. return false;
  76009. }
  76010. var emitterPosition = this.getEmitterPosition();
  76011. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  76012. var distance = direction.length();
  76013. direction.normalize();
  76014. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  76015. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  76016. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  76017. };
  76018. LensFlareSystem.prototype.render = function () {
  76019. if (!this._effect.isReady() || !this._scene.activeCamera)
  76020. return false;
  76021. var engine = this._scene.getEngine();
  76022. var viewport = this._scene.activeCamera.viewport;
  76023. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  76024. // Position
  76025. if (!this.computeEffectivePosition(globalViewport)) {
  76026. return false;
  76027. }
  76028. // Visibility
  76029. if (!this._isVisible()) {
  76030. return false;
  76031. }
  76032. // Intensity
  76033. var awayX;
  76034. var awayY;
  76035. if (this._positionX < this.borderLimit + globalViewport.x) {
  76036. awayX = this.borderLimit + globalViewport.x - this._positionX;
  76037. }
  76038. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  76039. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  76040. }
  76041. else {
  76042. awayX = 0;
  76043. }
  76044. if (this._positionY < this.borderLimit + globalViewport.y) {
  76045. awayY = this.borderLimit + globalViewport.y - this._positionY;
  76046. }
  76047. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  76048. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  76049. }
  76050. else {
  76051. awayY = 0;
  76052. }
  76053. var away = (awayX > awayY) ? awayX : awayY;
  76054. away -= this.viewportBorder;
  76055. if (away > this.borderLimit) {
  76056. away = this.borderLimit;
  76057. }
  76058. var intensity = 1.0 - (away / this.borderLimit);
  76059. if (intensity < 0) {
  76060. return false;
  76061. }
  76062. if (intensity > 1.0) {
  76063. intensity = 1.0;
  76064. }
  76065. if (this.viewportBorder > 0) {
  76066. globalViewport.x += this.viewportBorder;
  76067. globalViewport.y += this.viewportBorder;
  76068. globalViewport.width -= this.viewportBorder * 2;
  76069. globalViewport.height -= this.viewportBorder * 2;
  76070. this._positionX -= this.viewportBorder;
  76071. this._positionY -= this.viewportBorder;
  76072. }
  76073. // Position
  76074. var centerX = globalViewport.x + globalViewport.width / 2;
  76075. var centerY = globalViewport.y + globalViewport.height / 2;
  76076. var distX = centerX - this._positionX;
  76077. var distY = centerY - this._positionY;
  76078. // Effects
  76079. engine.enableEffect(this._effect);
  76080. engine.setState(false);
  76081. engine.setDepthBuffer(false);
  76082. // VBOs
  76083. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  76084. // Flares
  76085. for (var index = 0; index < this.lensFlares.length; index++) {
  76086. var flare = this.lensFlares[index];
  76087. engine.setAlphaMode(flare.alphaMode);
  76088. var x = centerX - (distX * flare.position);
  76089. var y = centerY - (distY * flare.position);
  76090. var cw = flare.size;
  76091. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  76092. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  76093. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  76094. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  76095. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  76096. // Texture
  76097. this._effect.setTexture("textureSampler", flare.texture);
  76098. // Color
  76099. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  76100. // Draw order
  76101. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76102. }
  76103. engine.setDepthBuffer(true);
  76104. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76105. return true;
  76106. };
  76107. LensFlareSystem.prototype.dispose = function () {
  76108. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76109. if (vertexBuffer) {
  76110. vertexBuffer.dispose();
  76111. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  76112. }
  76113. if (this._indexBuffer) {
  76114. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  76115. this._indexBuffer = null;
  76116. }
  76117. while (this.lensFlares.length) {
  76118. this.lensFlares[0].dispose();
  76119. }
  76120. // Remove from scene
  76121. var index = this._scene.lensFlareSystems.indexOf(this);
  76122. this._scene.lensFlareSystems.splice(index, 1);
  76123. };
  76124. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  76125. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  76126. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  76127. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  76128. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  76129. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  76130. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  76131. var parsedFlare = parsedLensFlareSystem.flares[index];
  76132. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  76133. }
  76134. return lensFlareSystem;
  76135. };
  76136. LensFlareSystem.prototype.serialize = function () {
  76137. var serializationObject = {};
  76138. serializationObject.id = this.id;
  76139. serializationObject.name = this.name;
  76140. serializationObject.emitterId = this.getEmitter().id;
  76141. serializationObject.borderLimit = this.borderLimit;
  76142. serializationObject.flares = [];
  76143. for (var index = 0; index < this.lensFlares.length; index++) {
  76144. var flare = this.lensFlares[index];
  76145. serializationObject.flares.push({
  76146. size: flare.size,
  76147. position: flare.position,
  76148. color: flare.color.asArray(),
  76149. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  76150. });
  76151. }
  76152. return serializationObject;
  76153. };
  76154. return LensFlareSystem;
  76155. }());
  76156. BABYLON.LensFlareSystem = LensFlareSystem;
  76157. })(BABYLON || (BABYLON = {}));
  76158. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  76159. "use strict";
  76160. var BABYLON;
  76161. (function (BABYLON) {
  76162. /**
  76163. * This is a holder class for the physics joint created by the physics plugin.
  76164. * It holds a set of functions to control the underlying joint.
  76165. */
  76166. var PhysicsJoint = /** @class */ (function () {
  76167. function PhysicsJoint(type, jointData) {
  76168. this.type = type;
  76169. this.jointData = jointData;
  76170. jointData.nativeParams = jointData.nativeParams || {};
  76171. }
  76172. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  76173. get: function () {
  76174. return this._physicsJoint;
  76175. },
  76176. set: function (newJoint) {
  76177. if (this._physicsJoint) {
  76178. //remove from the wolrd
  76179. }
  76180. this._physicsJoint = newJoint;
  76181. },
  76182. enumerable: true,
  76183. configurable: true
  76184. });
  76185. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  76186. set: function (physicsPlugin) {
  76187. this._physicsPlugin = physicsPlugin;
  76188. },
  76189. enumerable: true,
  76190. configurable: true
  76191. });
  76192. /**
  76193. * Execute a function that is physics-plugin specific.
  76194. * @param {Function} func the function that will be executed.
  76195. * It accepts two parameters: the physics world and the physics joint.
  76196. */
  76197. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  76198. func(this._physicsPlugin.world, this._physicsJoint);
  76199. };
  76200. //TODO check if the native joints are the same
  76201. //Joint Types
  76202. PhysicsJoint.DistanceJoint = 0;
  76203. PhysicsJoint.HingeJoint = 1;
  76204. PhysicsJoint.BallAndSocketJoint = 2;
  76205. PhysicsJoint.WheelJoint = 3;
  76206. PhysicsJoint.SliderJoint = 4;
  76207. //OIMO
  76208. PhysicsJoint.PrismaticJoint = 5;
  76209. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  76210. PhysicsJoint.UniversalJoint = 6;
  76211. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  76212. //Cannon
  76213. //Similar to a Ball-Joint. Different in params
  76214. PhysicsJoint.PointToPointJoint = 8;
  76215. //Cannon only at the moment
  76216. PhysicsJoint.SpringJoint = 9;
  76217. PhysicsJoint.LockJoint = 10;
  76218. return PhysicsJoint;
  76219. }());
  76220. BABYLON.PhysicsJoint = PhysicsJoint;
  76221. /**
  76222. * A class representing a physics distance joint.
  76223. */
  76224. var DistanceJoint = /** @class */ (function (_super) {
  76225. __extends(DistanceJoint, _super);
  76226. function DistanceJoint(jointData) {
  76227. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  76228. }
  76229. /**
  76230. * Update the predefined distance.
  76231. */
  76232. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  76233. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  76234. };
  76235. return DistanceJoint;
  76236. }(PhysicsJoint));
  76237. BABYLON.DistanceJoint = DistanceJoint;
  76238. var MotorEnabledJoint = /** @class */ (function (_super) {
  76239. __extends(MotorEnabledJoint, _super);
  76240. function MotorEnabledJoint(type, jointData) {
  76241. return _super.call(this, type, jointData) || this;
  76242. }
  76243. /**
  76244. * Set the motor values.
  76245. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76246. * @param {number} force the force to apply
  76247. * @param {number} maxForce max force for this motor.
  76248. */
  76249. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  76250. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  76251. };
  76252. /**
  76253. * Set the motor's limits.
  76254. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76255. */
  76256. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  76257. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  76258. };
  76259. return MotorEnabledJoint;
  76260. }(PhysicsJoint));
  76261. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  76262. /**
  76263. * This class represents a single hinge physics joint
  76264. */
  76265. var HingeJoint = /** @class */ (function (_super) {
  76266. __extends(HingeJoint, _super);
  76267. function HingeJoint(jointData) {
  76268. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  76269. }
  76270. /**
  76271. * Set the motor values.
  76272. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76273. * @param {number} force the force to apply
  76274. * @param {number} maxForce max force for this motor.
  76275. */
  76276. HingeJoint.prototype.setMotor = function (force, maxForce) {
  76277. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  76278. };
  76279. /**
  76280. * Set the motor's limits.
  76281. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76282. */
  76283. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  76284. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  76285. };
  76286. return HingeJoint;
  76287. }(MotorEnabledJoint));
  76288. BABYLON.HingeJoint = HingeJoint;
  76289. /**
  76290. * This class represents a dual hinge physics joint (same as wheel joint)
  76291. */
  76292. var Hinge2Joint = /** @class */ (function (_super) {
  76293. __extends(Hinge2Joint, _super);
  76294. function Hinge2Joint(jointData) {
  76295. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  76296. }
  76297. /**
  76298. * Set the motor values.
  76299. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76300. * @param {number} force the force to apply
  76301. * @param {number} maxForce max force for this motor.
  76302. * @param {motorIndex} the motor's index, 0 or 1.
  76303. */
  76304. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  76305. if (motorIndex === void 0) { motorIndex = 0; }
  76306. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  76307. };
  76308. /**
  76309. * Set the motor limits.
  76310. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76311. * @param {number} upperLimit the upper limit
  76312. * @param {number} lowerLimit lower limit
  76313. * @param {motorIndex} the motor's index, 0 or 1.
  76314. */
  76315. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  76316. if (motorIndex === void 0) { motorIndex = 0; }
  76317. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  76318. };
  76319. return Hinge2Joint;
  76320. }(MotorEnabledJoint));
  76321. BABYLON.Hinge2Joint = Hinge2Joint;
  76322. })(BABYLON || (BABYLON = {}));
  76323. //# sourceMappingURL=babylon.physicsJoint.js.map
  76324. "use strict";
  76325. var BABYLON;
  76326. (function (BABYLON) {
  76327. var PhysicsImpostor = /** @class */ (function () {
  76328. function PhysicsImpostor(object, type, _options, _scene) {
  76329. if (_options === void 0) { _options = { mass: 0 }; }
  76330. var _this = this;
  76331. this.object = object;
  76332. this.type = type;
  76333. this._options = _options;
  76334. this._scene = _scene;
  76335. this._bodyUpdateRequired = false;
  76336. this._onBeforePhysicsStepCallbacks = new Array();
  76337. this._onAfterPhysicsStepCallbacks = new Array();
  76338. this._onPhysicsCollideCallbacks = [];
  76339. this._deltaPosition = BABYLON.Vector3.Zero();
  76340. this._isDisposed = false;
  76341. //temp variables for parent rotation calculations
  76342. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  76343. this._tmpQuat = new BABYLON.Quaternion();
  76344. this._tmpQuat2 = new BABYLON.Quaternion();
  76345. /**
  76346. * this function is executed by the physics engine.
  76347. */
  76348. this.beforeStep = function () {
  76349. if (!_this._physicsEngine) {
  76350. return;
  76351. }
  76352. _this.object.translate(_this._deltaPosition, -1);
  76353. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  76354. _this.object.computeWorldMatrix(false);
  76355. if (_this.object.parent && _this.object.rotationQuaternion) {
  76356. _this.getParentsRotation();
  76357. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  76358. }
  76359. else {
  76360. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  76361. }
  76362. if (!_this._options.disableBidirectionalTransformation) {
  76363. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  76364. }
  76365. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  76366. func(_this);
  76367. });
  76368. };
  76369. /**
  76370. * this function is executed by the physics engine.
  76371. */
  76372. this.afterStep = function () {
  76373. if (!_this._physicsEngine) {
  76374. return;
  76375. }
  76376. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  76377. func(_this);
  76378. });
  76379. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  76380. // object has now its world rotation. needs to be converted to local.
  76381. if (_this.object.parent && _this.object.rotationQuaternion) {
  76382. _this.getParentsRotation();
  76383. _this._tmpQuat.conjugateInPlace();
  76384. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  76385. }
  76386. // take the position set and make it the absolute position of this object.
  76387. _this.object.setAbsolutePosition(_this.object.position);
  76388. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  76389. _this.object.translate(_this._deltaPosition, 1);
  76390. };
  76391. /**
  76392. * Legacy collision detection event support
  76393. */
  76394. this.onCollideEvent = null;
  76395. //event and body object due to cannon's event-based architecture.
  76396. this.onCollide = function (e) {
  76397. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  76398. return;
  76399. }
  76400. if (!_this._physicsEngine) {
  76401. return;
  76402. }
  76403. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  76404. if (otherImpostor) {
  76405. // Legacy collision detection event support
  76406. if (_this.onCollideEvent) {
  76407. _this.onCollideEvent(_this, otherImpostor);
  76408. }
  76409. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  76410. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  76411. }).forEach(function (obj) {
  76412. obj.callback(_this, otherImpostor);
  76413. });
  76414. }
  76415. };
  76416. //sanity check!
  76417. if (!this.object) {
  76418. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  76419. return;
  76420. }
  76421. //legacy support for old syntax.
  76422. if (!this._scene && object.getScene) {
  76423. this._scene = object.getScene();
  76424. }
  76425. if (!this._scene) {
  76426. return;
  76427. }
  76428. this._physicsEngine = this._scene.getPhysicsEngine();
  76429. if (!this._physicsEngine) {
  76430. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  76431. }
  76432. else {
  76433. //set the object's quaternion, if not set
  76434. if (!this.object.rotationQuaternion) {
  76435. if (this.object.rotation) {
  76436. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  76437. }
  76438. else {
  76439. this.object.rotationQuaternion = new BABYLON.Quaternion();
  76440. }
  76441. }
  76442. //default options params
  76443. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  76444. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  76445. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  76446. this._joints = [];
  76447. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  76448. if (!this.object.parent || this._options.ignoreParent) {
  76449. this._init();
  76450. }
  76451. else if (this.object.parent.physicsImpostor) {
  76452. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  76453. }
  76454. }
  76455. }
  76456. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  76457. get: function () {
  76458. return this._isDisposed;
  76459. },
  76460. enumerable: true,
  76461. configurable: true
  76462. });
  76463. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  76464. get: function () {
  76465. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  76466. },
  76467. set: function (value) {
  76468. this.setMass(value);
  76469. },
  76470. enumerable: true,
  76471. configurable: true
  76472. });
  76473. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  76474. get: function () {
  76475. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  76476. },
  76477. set: function (value) {
  76478. if (!this._physicsEngine) {
  76479. return;
  76480. }
  76481. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  76482. },
  76483. enumerable: true,
  76484. configurable: true
  76485. });
  76486. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  76487. get: function () {
  76488. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  76489. },
  76490. set: function (value) {
  76491. if (!this._physicsEngine) {
  76492. return;
  76493. }
  76494. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  76495. },
  76496. enumerable: true,
  76497. configurable: true
  76498. });
  76499. /**
  76500. * This function will completly initialize this impostor.
  76501. * It will create a new body - but only if this mesh has no parent.
  76502. * If it has, this impostor will not be used other than to define the impostor
  76503. * of the child mesh.
  76504. */
  76505. PhysicsImpostor.prototype._init = function () {
  76506. if (!this._physicsEngine) {
  76507. return;
  76508. }
  76509. this._physicsEngine.removeImpostor(this);
  76510. this.physicsBody = null;
  76511. this._parent = this._parent || this._getPhysicsParent();
  76512. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  76513. this._physicsEngine.addImpostor(this);
  76514. }
  76515. };
  76516. PhysicsImpostor.prototype._getPhysicsParent = function () {
  76517. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  76518. var parentMesh = this.object.parent;
  76519. return parentMesh.physicsImpostor;
  76520. }
  76521. return null;
  76522. };
  76523. /**
  76524. * Should a new body be generated.
  76525. */
  76526. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  76527. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  76528. };
  76529. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  76530. this.forceUpdate();
  76531. };
  76532. /**
  76533. * Force a regeneration of this or the parent's impostor's body.
  76534. * Use under cautious - This will remove all joints already implemented.
  76535. */
  76536. PhysicsImpostor.prototype.forceUpdate = function () {
  76537. this._init();
  76538. if (this.parent && !this._options.ignoreParent) {
  76539. this.parent.forceUpdate();
  76540. }
  76541. };
  76542. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  76543. /*public get mesh(): AbstractMesh {
  76544. return this._mesh;
  76545. }*/
  76546. /**
  76547. * Gets the body that holds this impostor. Either its own, or its parent.
  76548. */
  76549. get: function () {
  76550. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  76551. },
  76552. /**
  76553. * Set the physics body. Used mainly by the physics engine/plugin
  76554. */
  76555. set: function (physicsBody) {
  76556. if (this._physicsBody && this._physicsEngine) {
  76557. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  76558. }
  76559. this._physicsBody = physicsBody;
  76560. this.resetUpdateFlags();
  76561. },
  76562. enumerable: true,
  76563. configurable: true
  76564. });
  76565. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  76566. get: function () {
  76567. return !this._options.ignoreParent && this._parent ? this._parent : null;
  76568. },
  76569. set: function (value) {
  76570. this._parent = value;
  76571. },
  76572. enumerable: true,
  76573. configurable: true
  76574. });
  76575. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  76576. this._bodyUpdateRequired = false;
  76577. };
  76578. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  76579. if (this.object.getBoundingInfo) {
  76580. var q = this.object.rotationQuaternion;
  76581. //reset rotation
  76582. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  76583. //calculate the world matrix with no rotation
  76584. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  76585. var boundingInfo = this.object.getBoundingInfo();
  76586. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  76587. //bring back the rotation
  76588. this.object.rotationQuaternion = q;
  76589. //calculate the world matrix with the new rotation
  76590. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  76591. return size;
  76592. }
  76593. else {
  76594. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  76595. }
  76596. };
  76597. PhysicsImpostor.prototype.getObjectCenter = function () {
  76598. if (this.object.getBoundingInfo) {
  76599. var boundingInfo = this.object.getBoundingInfo();
  76600. return boundingInfo.boundingBox.centerWorld;
  76601. }
  76602. else {
  76603. return this.object.position;
  76604. }
  76605. };
  76606. /**
  76607. * Get a specific parametes from the options parameter.
  76608. */
  76609. PhysicsImpostor.prototype.getParam = function (paramName) {
  76610. return this._options[paramName];
  76611. };
  76612. /**
  76613. * Sets a specific parameter in the options given to the physics plugin
  76614. */
  76615. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  76616. this._options[paramName] = value;
  76617. this._bodyUpdateRequired = true;
  76618. };
  76619. /**
  76620. * Specifically change the body's mass option. Won't recreate the physics body object
  76621. */
  76622. PhysicsImpostor.prototype.setMass = function (mass) {
  76623. if (this.getParam("mass") !== mass) {
  76624. this.setParam("mass", mass);
  76625. }
  76626. if (this._physicsEngine) {
  76627. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  76628. }
  76629. };
  76630. PhysicsImpostor.prototype.getLinearVelocity = function () {
  76631. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  76632. };
  76633. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  76634. if (this._physicsEngine) {
  76635. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  76636. }
  76637. };
  76638. PhysicsImpostor.prototype.getAngularVelocity = function () {
  76639. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  76640. };
  76641. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  76642. if (this._physicsEngine) {
  76643. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  76644. }
  76645. };
  76646. /**
  76647. * Execute a function with the physics plugin native code.
  76648. * Provide a function the will have two variables - the world object and the physics body object.
  76649. */
  76650. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  76651. if (this._physicsEngine) {
  76652. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  76653. }
  76654. };
  76655. /**
  76656. * Register a function that will be executed before the physics world is stepping forward.
  76657. */
  76658. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  76659. this._onBeforePhysicsStepCallbacks.push(func);
  76660. };
  76661. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  76662. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  76663. if (index > -1) {
  76664. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  76665. }
  76666. else {
  76667. BABYLON.Tools.Warn("Function to remove was not found");
  76668. }
  76669. };
  76670. /**
  76671. * Register a function that will be executed after the physics step
  76672. */
  76673. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  76674. this._onAfterPhysicsStepCallbacks.push(func);
  76675. };
  76676. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  76677. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  76678. if (index > -1) {
  76679. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  76680. }
  76681. else {
  76682. BABYLON.Tools.Warn("Function to remove was not found");
  76683. }
  76684. };
  76685. /**
  76686. * register a function that will be executed when this impostor collides against a different body.
  76687. */
  76688. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  76689. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  76690. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  76691. };
  76692. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  76693. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  76694. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  76695. if (index > -1) {
  76696. this._onPhysicsCollideCallbacks.splice(index, 1);
  76697. }
  76698. else {
  76699. BABYLON.Tools.Warn("Function to remove was not found");
  76700. }
  76701. };
  76702. PhysicsImpostor.prototype.getParentsRotation = function () {
  76703. var parent = this.object.parent;
  76704. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  76705. while (parent) {
  76706. if (parent.rotationQuaternion) {
  76707. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  76708. }
  76709. else {
  76710. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  76711. }
  76712. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  76713. parent = parent.parent;
  76714. }
  76715. return this._tmpQuat;
  76716. };
  76717. /**
  76718. * Apply a force
  76719. */
  76720. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  76721. if (this._physicsEngine) {
  76722. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  76723. }
  76724. return this;
  76725. };
  76726. /**
  76727. * Apply an impulse
  76728. */
  76729. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  76730. if (this._physicsEngine) {
  76731. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  76732. }
  76733. return this;
  76734. };
  76735. /**
  76736. * A help function to create a joint.
  76737. */
  76738. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  76739. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  76740. this.addJoint(otherImpostor, joint);
  76741. return this;
  76742. };
  76743. /**
  76744. * Add a joint to this impostor with a different impostor.
  76745. */
  76746. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  76747. this._joints.push({
  76748. otherImpostor: otherImpostor,
  76749. joint: joint
  76750. });
  76751. if (this._physicsEngine) {
  76752. this._physicsEngine.addJoint(this, otherImpostor, joint);
  76753. }
  76754. return this;
  76755. };
  76756. /**
  76757. * Will keep this body still, in a sleep mode.
  76758. */
  76759. PhysicsImpostor.prototype.sleep = function () {
  76760. if (this._physicsEngine) {
  76761. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  76762. }
  76763. return this;
  76764. };
  76765. /**
  76766. * Wake the body up.
  76767. */
  76768. PhysicsImpostor.prototype.wakeUp = function () {
  76769. if (this._physicsEngine) {
  76770. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  76771. }
  76772. return this;
  76773. };
  76774. PhysicsImpostor.prototype.clone = function (newObject) {
  76775. if (!newObject)
  76776. return null;
  76777. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  76778. };
  76779. PhysicsImpostor.prototype.dispose = function () {
  76780. var _this = this;
  76781. //no dispose if no physics engine is available.
  76782. if (!this._physicsEngine) {
  76783. return;
  76784. }
  76785. this._joints.forEach(function (j) {
  76786. if (_this._physicsEngine) {
  76787. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  76788. }
  76789. });
  76790. //dispose the physics body
  76791. this._physicsEngine.removeImpostor(this);
  76792. if (this.parent) {
  76793. this.parent.forceUpdate();
  76794. }
  76795. else {
  76796. /*this._object.getChildMeshes().forEach(function(mesh) {
  76797. if (mesh.physicsImpostor) {
  76798. if (disposeChildren) {
  76799. mesh.physicsImpostor.dispose();
  76800. mesh.physicsImpostor = null;
  76801. }
  76802. }
  76803. })*/
  76804. }
  76805. this._isDisposed = true;
  76806. };
  76807. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  76808. this._deltaPosition.copyFrom(position);
  76809. };
  76810. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  76811. if (!this._deltaRotation) {
  76812. this._deltaRotation = new BABYLON.Quaternion();
  76813. }
  76814. this._deltaRotation.copyFrom(rotation);
  76815. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  76816. };
  76817. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  76818. if (this._physicsEngine) {
  76819. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  76820. }
  76821. return this;
  76822. };
  76823. PhysicsImpostor.prototype.getRadius = function () {
  76824. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  76825. };
  76826. /**
  76827. * Sync a bone with this impostor
  76828. * @param bone The bone to sync to the impostor.
  76829. * @param boneMesh The mesh that the bone is influencing.
  76830. * @param jointPivot The pivot of the joint / bone in local space.
  76831. * @param distToJoint Optional distance from the impostor to the joint.
  76832. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  76833. */
  76834. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  76835. var tempVec = PhysicsImpostor._tmpVecs[0];
  76836. var mesh = this.object;
  76837. if (mesh.rotationQuaternion) {
  76838. if (adjustRotation) {
  76839. var tempQuat = PhysicsImpostor._tmpQuat;
  76840. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  76841. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  76842. }
  76843. else {
  76844. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  76845. }
  76846. }
  76847. tempVec.x = 0;
  76848. tempVec.y = 0;
  76849. tempVec.z = 0;
  76850. if (jointPivot) {
  76851. tempVec.x = jointPivot.x;
  76852. tempVec.y = jointPivot.y;
  76853. tempVec.z = jointPivot.z;
  76854. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  76855. if (distToJoint === undefined || distToJoint === null) {
  76856. distToJoint = jointPivot.length();
  76857. }
  76858. tempVec.x *= distToJoint;
  76859. tempVec.y *= distToJoint;
  76860. tempVec.z *= distToJoint;
  76861. }
  76862. if (bone.getParent()) {
  76863. tempVec.addInPlace(mesh.getAbsolutePosition());
  76864. bone.setAbsolutePosition(tempVec, boneMesh);
  76865. }
  76866. else {
  76867. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  76868. boneMesh.position.x -= tempVec.x;
  76869. boneMesh.position.y -= tempVec.y;
  76870. boneMesh.position.z -= tempVec.z;
  76871. }
  76872. };
  76873. /**
  76874. * Sync impostor to a bone
  76875. * @param bone The bone that the impostor will be synced to.
  76876. * @param boneMesh The mesh that the bone is influencing.
  76877. * @param jointPivot The pivot of the joint / bone in local space.
  76878. * @param distToJoint Optional distance from the impostor to the joint.
  76879. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  76880. * @param boneAxis Optional vector3 axis the bone is aligned with
  76881. */
  76882. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  76883. var mesh = this.object;
  76884. if (mesh.rotationQuaternion) {
  76885. if (adjustRotation) {
  76886. var tempQuat = PhysicsImpostor._tmpQuat;
  76887. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  76888. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  76889. }
  76890. else {
  76891. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  76892. }
  76893. }
  76894. var pos = PhysicsImpostor._tmpVecs[0];
  76895. var boneDir = PhysicsImpostor._tmpVecs[1];
  76896. if (!boneAxis) {
  76897. boneAxis = PhysicsImpostor._tmpVecs[2];
  76898. boneAxis.x = 0;
  76899. boneAxis.y = 1;
  76900. boneAxis.z = 0;
  76901. }
  76902. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  76903. bone.getAbsolutePositionToRef(boneMesh, pos);
  76904. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  76905. distToJoint = jointPivot.length();
  76906. }
  76907. if (distToJoint !== undefined && distToJoint !== null) {
  76908. pos.x += boneDir.x * distToJoint;
  76909. pos.y += boneDir.y * distToJoint;
  76910. pos.z += boneDir.z * distToJoint;
  76911. }
  76912. mesh.setAbsolutePosition(pos);
  76913. };
  76914. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  76915. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  76916. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76917. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  76918. //Impostor types
  76919. PhysicsImpostor.NoImpostor = 0;
  76920. PhysicsImpostor.SphereImpostor = 1;
  76921. PhysicsImpostor.BoxImpostor = 2;
  76922. PhysicsImpostor.PlaneImpostor = 3;
  76923. PhysicsImpostor.MeshImpostor = 4;
  76924. PhysicsImpostor.CylinderImpostor = 7;
  76925. PhysicsImpostor.ParticleImpostor = 8;
  76926. PhysicsImpostor.HeightmapImpostor = 9;
  76927. return PhysicsImpostor;
  76928. }());
  76929. BABYLON.PhysicsImpostor = PhysicsImpostor;
  76930. })(BABYLON || (BABYLON = {}));
  76931. //# sourceMappingURL=babylon.physicsImpostor.js.map
  76932. "use strict";
  76933. var BABYLON;
  76934. (function (BABYLON) {
  76935. var PhysicsEngine = /** @class */ (function () {
  76936. function PhysicsEngine(gravity, _physicsPlugin) {
  76937. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  76938. this._physicsPlugin = _physicsPlugin;
  76939. //new methods and parameters
  76940. this._impostors = [];
  76941. this._joints = [];
  76942. if (!this._physicsPlugin.isSupported()) {
  76943. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  76944. + "Please make sure it is included.");
  76945. }
  76946. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  76947. this.setGravity(gravity);
  76948. this.setTimeStep();
  76949. }
  76950. PhysicsEngine.prototype.setGravity = function (gravity) {
  76951. this.gravity = gravity;
  76952. this._physicsPlugin.setGravity(this.gravity);
  76953. };
  76954. /**
  76955. * Set the time step of the physics engine.
  76956. * default is 1/60.
  76957. * To slow it down, enter 1/600 for example.
  76958. * To speed it up, 1/30
  76959. * @param {number} newTimeStep the new timestep to apply to this world.
  76960. */
  76961. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  76962. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  76963. this._physicsPlugin.setTimeStep(newTimeStep);
  76964. };
  76965. /**
  76966. * Get the time step of the physics engine.
  76967. */
  76968. PhysicsEngine.prototype.getTimeStep = function () {
  76969. return this._physicsPlugin.getTimeStep();
  76970. };
  76971. PhysicsEngine.prototype.dispose = function () {
  76972. this._impostors.forEach(function (impostor) {
  76973. impostor.dispose();
  76974. });
  76975. this._physicsPlugin.dispose();
  76976. };
  76977. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  76978. return this._physicsPlugin.name;
  76979. };
  76980. /**
  76981. * Adding a new impostor for the impostor tracking.
  76982. * This will be done by the impostor itself.
  76983. * @param {PhysicsImpostor} impostor the impostor to add
  76984. */
  76985. PhysicsEngine.prototype.addImpostor = function (impostor) {
  76986. impostor.uniqueId = this._impostors.push(impostor);
  76987. //if no parent, generate the body
  76988. if (!impostor.parent) {
  76989. this._physicsPlugin.generatePhysicsBody(impostor);
  76990. }
  76991. };
  76992. /**
  76993. * Remove an impostor from the engine.
  76994. * This impostor and its mesh will not longer be updated by the physics engine.
  76995. * @param {PhysicsImpostor} impostor the impostor to remove
  76996. */
  76997. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  76998. var index = this._impostors.indexOf(impostor);
  76999. if (index > -1) {
  77000. var removed = this._impostors.splice(index, 1);
  77001. //Is it needed?
  77002. if (removed.length) {
  77003. //this will also remove it from the world.
  77004. removed[0].physicsBody = null;
  77005. }
  77006. }
  77007. };
  77008. /**
  77009. * Add a joint to the physics engine
  77010. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  77011. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  77012. * @param {PhysicsJoint} the joint that will connect both impostors.
  77013. */
  77014. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  77015. var impostorJoint = {
  77016. mainImpostor: mainImpostor,
  77017. connectedImpostor: connectedImpostor,
  77018. joint: joint
  77019. };
  77020. joint.physicsPlugin = this._physicsPlugin;
  77021. this._joints.push(impostorJoint);
  77022. this._physicsPlugin.generateJoint(impostorJoint);
  77023. };
  77024. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  77025. var matchingJoints = this._joints.filter(function (impostorJoint) {
  77026. return (impostorJoint.connectedImpostor === connectedImpostor
  77027. && impostorJoint.joint === joint
  77028. && impostorJoint.mainImpostor === mainImpostor);
  77029. });
  77030. if (matchingJoints.length) {
  77031. this._physicsPlugin.removeJoint(matchingJoints[0]);
  77032. //TODO remove it from the list as well
  77033. }
  77034. };
  77035. /**
  77036. * Called by the scene. no need to call it.
  77037. */
  77038. PhysicsEngine.prototype._step = function (delta) {
  77039. var _this = this;
  77040. //check if any mesh has no body / requires an update
  77041. this._impostors.forEach(function (impostor) {
  77042. if (impostor.isBodyInitRequired()) {
  77043. _this._physicsPlugin.generatePhysicsBody(impostor);
  77044. }
  77045. });
  77046. if (delta > 0.1) {
  77047. delta = 0.1;
  77048. }
  77049. else if (delta <= 0) {
  77050. delta = 1.0 / 60.0;
  77051. }
  77052. this._physicsPlugin.executeStep(delta, this._impostors);
  77053. };
  77054. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  77055. return this._physicsPlugin;
  77056. };
  77057. PhysicsEngine.prototype.getImpostors = function () {
  77058. return this._impostors;
  77059. };
  77060. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  77061. for (var i = 0; i < this._impostors.length; ++i) {
  77062. if (this._impostors[i].object === object) {
  77063. return this._impostors[i];
  77064. }
  77065. }
  77066. return null;
  77067. };
  77068. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  77069. for (var i = 0; i < this._impostors.length; ++i) {
  77070. if (this._impostors[i].physicsBody === body) {
  77071. return this._impostors[i];
  77072. }
  77073. }
  77074. return null;
  77075. };
  77076. // Statics
  77077. PhysicsEngine.Epsilon = 0.001;
  77078. return PhysicsEngine;
  77079. }());
  77080. BABYLON.PhysicsEngine = PhysicsEngine;
  77081. })(BABYLON || (BABYLON = {}));
  77082. //# sourceMappingURL=babylon.physicsEngine.js.map
  77083. "use strict";
  77084. var BABYLON;
  77085. (function (BABYLON) {
  77086. var PhysicsHelper = /** @class */ (function () {
  77087. function PhysicsHelper(scene) {
  77088. this._scene = scene;
  77089. this._physicsEngine = this._scene.getPhysicsEngine();
  77090. if (!this._physicsEngine) {
  77091. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  77092. }
  77093. }
  77094. /**
  77095. * @param {Vector3} origin the origin of the explosion
  77096. * @param {number} radius the explosion radius
  77097. * @param {number} strength the explosion strength
  77098. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77099. */
  77100. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  77101. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77102. if (!this._physicsEngine) {
  77103. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  77104. return null;
  77105. }
  77106. var impostors = this._physicsEngine.getImpostors();
  77107. if (impostors.length === 0) {
  77108. return null;
  77109. }
  77110. var event = new PhysicsRadialExplosionEvent(this._scene);
  77111. impostors.forEach(function (impostor) {
  77112. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  77113. if (!impostorForceAndContactPoint) {
  77114. return;
  77115. }
  77116. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77117. });
  77118. event.dispose(false);
  77119. return event;
  77120. };
  77121. /**
  77122. * @param {Vector3} origin the origin of the explosion
  77123. * @param {number} radius the explosion radius
  77124. * @param {number} strength the explosion strength
  77125. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77126. */
  77127. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  77128. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77129. if (!this._physicsEngine) {
  77130. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77131. return null;
  77132. }
  77133. var impostors = this._physicsEngine.getImpostors();
  77134. if (impostors.length === 0) {
  77135. return null;
  77136. }
  77137. var event = new PhysicsRadialExplosionEvent(this._scene);
  77138. impostors.forEach(function (impostor) {
  77139. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  77140. if (!impostorForceAndContactPoint) {
  77141. return;
  77142. }
  77143. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77144. });
  77145. event.dispose(false);
  77146. return event;
  77147. };
  77148. /**
  77149. * @param {Vector3} origin the origin of the explosion
  77150. * @param {number} radius the explosion radius
  77151. * @param {number} strength the explosion strength
  77152. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77153. */
  77154. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  77155. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77156. if (!this._physicsEngine) {
  77157. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77158. return null;
  77159. }
  77160. var impostors = this._physicsEngine.getImpostors();
  77161. if (impostors.length === 0) {
  77162. return null;
  77163. }
  77164. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  77165. event.dispose(false);
  77166. return event;
  77167. };
  77168. /**
  77169. * @param {Vector3} origin the origin of the updraft
  77170. * @param {number} radius the radius of the updraft
  77171. * @param {number} strength the strength of the updraft
  77172. * @param {number} height the height of the updraft
  77173. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  77174. */
  77175. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  77176. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  77177. if (!this._physicsEngine) {
  77178. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77179. return null;
  77180. }
  77181. if (this._physicsEngine.getImpostors().length === 0) {
  77182. return null;
  77183. }
  77184. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  77185. event.dispose(false);
  77186. return event;
  77187. };
  77188. /**
  77189. * @param {Vector3} origin the of the vortex
  77190. * @param {number} radius the radius of the vortex
  77191. * @param {number} strength the strength of the vortex
  77192. * @param {number} height the height of the vortex
  77193. */
  77194. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  77195. if (!this._physicsEngine) {
  77196. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77197. return null;
  77198. }
  77199. if (this._physicsEngine.getImpostors().length === 0) {
  77200. return null;
  77201. }
  77202. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  77203. event.dispose(false);
  77204. return event;
  77205. };
  77206. return PhysicsHelper;
  77207. }());
  77208. BABYLON.PhysicsHelper = PhysicsHelper;
  77209. /***** Radial explosion *****/
  77210. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  77211. function PhysicsRadialExplosionEvent(scene) {
  77212. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  77213. this._rays = [];
  77214. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  77215. this._scene = scene;
  77216. }
  77217. /**
  77218. * Returns the data related to the radial explosion event (sphere & rays).
  77219. * @returns {PhysicsRadialExplosionEventData}
  77220. */
  77221. PhysicsRadialExplosionEvent.prototype.getData = function () {
  77222. this._dataFetched = true;
  77223. return {
  77224. sphere: this._sphere,
  77225. rays: this._rays,
  77226. };
  77227. };
  77228. /**
  77229. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  77230. * @param impostor
  77231. * @param {Vector3} origin the origin of the explosion
  77232. * @param {number} radius the explosion radius
  77233. * @param {number} strength the explosion strength
  77234. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  77235. * @returns {Nullable<PhysicsForceAndContactPoint>}
  77236. */
  77237. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  77238. if (impostor.mass === 0) {
  77239. return null;
  77240. }
  77241. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  77242. return null;
  77243. }
  77244. if (impostor.object.getClassName() !== 'Mesh') {
  77245. return null;
  77246. }
  77247. var impostorObject = impostor.object;
  77248. var impostorObjectCenter = impostor.getObjectCenter();
  77249. var direction = impostorObjectCenter.subtract(origin);
  77250. var ray = new BABYLON.Ray(origin, direction, radius);
  77251. this._rays.push(ray);
  77252. var hit = ray.intersectsMesh(impostorObject);
  77253. var contactPoint = hit.pickedPoint;
  77254. if (!contactPoint) {
  77255. return null;
  77256. }
  77257. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  77258. if (distanceFromOrigin > radius) {
  77259. return null;
  77260. }
  77261. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  77262. ? strength
  77263. : strength * (1 - (distanceFromOrigin / radius));
  77264. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  77265. return { force: force, contactPoint: contactPoint };
  77266. };
  77267. /**
  77268. * Disposes the sphere.
  77269. * @param {bolean} force
  77270. */
  77271. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  77272. var _this = this;
  77273. if (force === void 0) { force = true; }
  77274. if (force) {
  77275. this._sphere.dispose();
  77276. }
  77277. else {
  77278. setTimeout(function () {
  77279. if (!_this._dataFetched) {
  77280. _this._sphere.dispose();
  77281. }
  77282. }, 0);
  77283. }
  77284. };
  77285. /*** Helpers ***/
  77286. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  77287. if (!this._sphere) {
  77288. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  77289. this._sphere.isVisible = false;
  77290. }
  77291. };
  77292. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  77293. var impostorObject = impostor.object;
  77294. this._prepareSphere();
  77295. this._sphere.position = origin;
  77296. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  77297. this._sphere._updateBoundingInfo();
  77298. this._sphere.computeWorldMatrix(true);
  77299. return this._sphere.intersectsMesh(impostorObject, true);
  77300. };
  77301. return PhysicsRadialExplosionEvent;
  77302. }());
  77303. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  77304. /***** Gravitational Field *****/
  77305. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  77306. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  77307. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77308. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77309. this._physicsHelper = physicsHelper;
  77310. this._scene = scene;
  77311. this._origin = origin;
  77312. this._radius = radius;
  77313. this._strength = strength;
  77314. this._falloff = falloff;
  77315. this._tickCallback = this._tick.bind(this);
  77316. }
  77317. /**
  77318. * Returns the data related to the gravitational field event (sphere).
  77319. * @returns {PhysicsGravitationalFieldEventData}
  77320. */
  77321. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  77322. this._dataFetched = true;
  77323. return {
  77324. sphere: this._sphere,
  77325. };
  77326. };
  77327. /**
  77328. * Enables the gravitational field.
  77329. */
  77330. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  77331. this._tickCallback.call(this);
  77332. this._scene.registerBeforeRender(this._tickCallback);
  77333. };
  77334. /**
  77335. * Disables the gravitational field.
  77336. */
  77337. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  77338. this._scene.unregisterBeforeRender(this._tickCallback);
  77339. };
  77340. /**
  77341. * Disposes the sphere.
  77342. * @param {bolean} force
  77343. */
  77344. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  77345. var _this = this;
  77346. if (force === void 0) { force = true; }
  77347. if (force) {
  77348. this._sphere.dispose();
  77349. }
  77350. else {
  77351. setTimeout(function () {
  77352. if (!_this._dataFetched) {
  77353. _this._sphere.dispose();
  77354. }
  77355. }, 0);
  77356. }
  77357. };
  77358. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  77359. // Since the params won't change, we fetch the event only once
  77360. if (this._sphere) {
  77361. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  77362. }
  77363. else {
  77364. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  77365. if (radialExplosionEvent) {
  77366. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  77367. }
  77368. }
  77369. };
  77370. return PhysicsGravitationalFieldEvent;
  77371. }());
  77372. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  77373. /***** Updraft *****/
  77374. var PhysicsUpdraftEvent = /** @class */ (function () {
  77375. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  77376. this._scene = _scene;
  77377. this._origin = _origin;
  77378. this._radius = _radius;
  77379. this._strength = _strength;
  77380. this._height = _height;
  77381. this._updraftMode = _updraftMode;
  77382. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  77383. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  77384. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  77385. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77386. this._physicsEngine = this._scene.getPhysicsEngine();
  77387. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  77388. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  77389. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  77390. this._originDirection = this._origin.subtract(this._originTop).normalize();
  77391. }
  77392. this._tickCallback = this._tick.bind(this);
  77393. }
  77394. /**
  77395. * Returns the data related to the updraft event (cylinder).
  77396. * @returns {PhysicsUpdraftEventData}
  77397. */
  77398. PhysicsUpdraftEvent.prototype.getData = function () {
  77399. this._dataFetched = true;
  77400. return {
  77401. cylinder: this._cylinder,
  77402. };
  77403. };
  77404. /**
  77405. * Enables the updraft.
  77406. */
  77407. PhysicsUpdraftEvent.prototype.enable = function () {
  77408. this._tickCallback.call(this);
  77409. this._scene.registerBeforeRender(this._tickCallback);
  77410. };
  77411. /**
  77412. * Disables the cortex.
  77413. */
  77414. PhysicsUpdraftEvent.prototype.disable = function () {
  77415. this._scene.unregisterBeforeRender(this._tickCallback);
  77416. };
  77417. /**
  77418. * Disposes the sphere.
  77419. * @param {bolean} force
  77420. */
  77421. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  77422. var _this = this;
  77423. if (force === void 0) { force = true; }
  77424. if (force) {
  77425. this._cylinder.dispose();
  77426. }
  77427. else {
  77428. setTimeout(function () {
  77429. if (!_this._dataFetched) {
  77430. _this._cylinder.dispose();
  77431. }
  77432. }, 0);
  77433. }
  77434. };
  77435. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  77436. if (impostor.mass === 0) {
  77437. return null;
  77438. }
  77439. if (!this._intersectsWithCylinder(impostor)) {
  77440. return null;
  77441. }
  77442. var impostorObjectCenter = impostor.getObjectCenter();
  77443. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  77444. var direction = this._originDirection;
  77445. }
  77446. else {
  77447. var direction = impostorObjectCenter.subtract(this._originTop);
  77448. }
  77449. var multiplier = this._strength * -1;
  77450. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  77451. return { force: force, contactPoint: impostorObjectCenter };
  77452. };
  77453. PhysicsUpdraftEvent.prototype._tick = function () {
  77454. var _this = this;
  77455. this._physicsEngine.getImpostors().forEach(function (impostor) {
  77456. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  77457. if (!impostorForceAndContactPoint) {
  77458. return;
  77459. }
  77460. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77461. });
  77462. };
  77463. /*** Helpers ***/
  77464. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  77465. if (!this._cylinder) {
  77466. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  77467. height: this._height,
  77468. diameter: this._radius * 2,
  77469. }, this._scene);
  77470. this._cylinder.isVisible = false;
  77471. }
  77472. };
  77473. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  77474. var impostorObject = impostor.object;
  77475. this._prepareCylinder();
  77476. this._cylinder.position = this._cylinderPosition;
  77477. return this._cylinder.intersectsMesh(impostorObject, true);
  77478. };
  77479. return PhysicsUpdraftEvent;
  77480. }());
  77481. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  77482. /***** Vortex *****/
  77483. var PhysicsVortexEvent = /** @class */ (function () {
  77484. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  77485. this._scene = _scene;
  77486. this._origin = _origin;
  77487. this._radius = _radius;
  77488. this._strength = _strength;
  77489. this._height = _height;
  77490. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  77491. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  77492. this._updraftMultiplier = 0.02;
  77493. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  77494. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77495. this._physicsEngine = this._scene.getPhysicsEngine();
  77496. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  77497. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  77498. this._tickCallback = this._tick.bind(this);
  77499. }
  77500. /**
  77501. * Returns the data related to the vortex event (cylinder).
  77502. * @returns {PhysicsVortexEventData}
  77503. */
  77504. PhysicsVortexEvent.prototype.getData = function () {
  77505. this._dataFetched = true;
  77506. return {
  77507. cylinder: this._cylinder,
  77508. };
  77509. };
  77510. /**
  77511. * Enables the vortex.
  77512. */
  77513. PhysicsVortexEvent.prototype.enable = function () {
  77514. this._tickCallback.call(this);
  77515. this._scene.registerBeforeRender(this._tickCallback);
  77516. };
  77517. /**
  77518. * Disables the cortex.
  77519. */
  77520. PhysicsVortexEvent.prototype.disable = function () {
  77521. this._scene.unregisterBeforeRender(this._tickCallback);
  77522. };
  77523. /**
  77524. * Disposes the sphere.
  77525. * @param {bolean} force
  77526. */
  77527. PhysicsVortexEvent.prototype.dispose = function (force) {
  77528. var _this = this;
  77529. if (force === void 0) { force = true; }
  77530. if (force) {
  77531. this._cylinder.dispose();
  77532. }
  77533. else {
  77534. setTimeout(function () {
  77535. if (!_this._dataFetched) {
  77536. _this._cylinder.dispose();
  77537. }
  77538. }, 0);
  77539. }
  77540. };
  77541. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  77542. if (impostor.mass === 0) {
  77543. return null;
  77544. }
  77545. if (!this._intersectsWithCylinder(impostor)) {
  77546. return null;
  77547. }
  77548. if (impostor.object.getClassName() !== 'Mesh') {
  77549. return null;
  77550. }
  77551. var impostorObject = impostor.object;
  77552. var impostorObjectCenter = impostor.getObjectCenter();
  77553. 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)
  77554. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  77555. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  77556. var hit = ray.intersectsMesh(impostorObject);
  77557. var contactPoint = hit.pickedPoint;
  77558. if (!contactPoint) {
  77559. return null;
  77560. }
  77561. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  77562. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  77563. var directionToOrigin = contactPoint.normalize();
  77564. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  77565. directionToOrigin = directionToOrigin.negate();
  77566. }
  77567. // TODO: find a more physically based solution
  77568. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  77569. var forceX = directionToOrigin.x * this._strength / 8;
  77570. var forceY = directionToOrigin.y * this._updraftMultiplier;
  77571. var forceZ = directionToOrigin.z * this._strength / 8;
  77572. }
  77573. else {
  77574. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  77575. var forceY = this._originTop.y * this._updraftMultiplier;
  77576. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  77577. }
  77578. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  77579. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  77580. return { force: force, contactPoint: impostorObjectCenter };
  77581. };
  77582. PhysicsVortexEvent.prototype._tick = function () {
  77583. var _this = this;
  77584. this._physicsEngine.getImpostors().forEach(function (impostor) {
  77585. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  77586. if (!impostorForceAndContactPoint) {
  77587. return;
  77588. }
  77589. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77590. });
  77591. };
  77592. /*** Helpers ***/
  77593. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  77594. if (!this._cylinder) {
  77595. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  77596. height: this._height,
  77597. diameter: this._radius * 2,
  77598. }, this._scene);
  77599. this._cylinder.isVisible = false;
  77600. }
  77601. };
  77602. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  77603. var impostorObject = impostor.object;
  77604. this._prepareCylinder();
  77605. this._cylinder.position = this._cylinderPosition;
  77606. return this._cylinder.intersectsMesh(impostorObject, true);
  77607. };
  77608. return PhysicsVortexEvent;
  77609. }());
  77610. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  77611. /***** Enums *****/
  77612. /**
  77613. * The strenght of the force in correspondence to the distance of the affected object
  77614. */
  77615. var PhysicsRadialImpulseFalloff;
  77616. (function (PhysicsRadialImpulseFalloff) {
  77617. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  77618. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  77619. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  77620. /**
  77621. * The strenght of the force in correspondence to the distance of the affected object
  77622. */
  77623. var PhysicsUpdraftMode;
  77624. (function (PhysicsUpdraftMode) {
  77625. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  77626. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  77627. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  77628. })(BABYLON || (BABYLON = {}));
  77629. //# sourceMappingURL=babylon.physicsHelper.js.map
  77630. "use strict";
  77631. var BABYLON;
  77632. (function (BABYLON) {
  77633. var CannonJSPlugin = /** @class */ (function () {
  77634. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  77635. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  77636. if (iterations === void 0) { iterations = 10; }
  77637. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  77638. this.name = "CannonJSPlugin";
  77639. this._physicsMaterials = new Array();
  77640. this._fixedTimeStep = 1 / 60;
  77641. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  77642. this.BJSCANNON = CANNON;
  77643. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  77644. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  77645. this._tmpPosition = BABYLON.Vector3.Zero();
  77646. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  77647. this._tmpUnityRotation = new BABYLON.Quaternion();
  77648. if (!this.isSupported()) {
  77649. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  77650. return;
  77651. }
  77652. this._extendNamespace();
  77653. this.world = new this.BJSCANNON.World();
  77654. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  77655. this.world.solver.iterations = iterations;
  77656. }
  77657. CannonJSPlugin.prototype.setGravity = function (gravity) {
  77658. this.world.gravity.copy(gravity);
  77659. };
  77660. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  77661. this._fixedTimeStep = timeStep;
  77662. };
  77663. CannonJSPlugin.prototype.getTimeStep = function () {
  77664. return this._fixedTimeStep;
  77665. };
  77666. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  77667. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  77668. };
  77669. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  77670. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  77671. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  77672. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  77673. };
  77674. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  77675. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  77676. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  77677. impostor.physicsBody.applyForce(impulse, worldPoint);
  77678. };
  77679. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  77680. //parent-child relationship. Does this impostor has a parent impostor?
  77681. if (impostor.parent) {
  77682. if (impostor.physicsBody) {
  77683. this.removePhysicsBody(impostor);
  77684. //TODO is that needed?
  77685. impostor.forceUpdate();
  77686. }
  77687. return;
  77688. }
  77689. //should a new body be created for this impostor?
  77690. if (impostor.isBodyInitRequired()) {
  77691. var shape = this._createShape(impostor);
  77692. //unregister events, if body is being changed
  77693. var oldBody = impostor.physicsBody;
  77694. if (oldBody) {
  77695. this.removePhysicsBody(impostor);
  77696. }
  77697. //create the body and material
  77698. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  77699. var bodyCreationObject = {
  77700. mass: impostor.getParam("mass"),
  77701. material: material
  77702. };
  77703. // A simple extend, in case native options were used.
  77704. var nativeOptions = impostor.getParam("nativeOptions");
  77705. for (var key in nativeOptions) {
  77706. if (nativeOptions.hasOwnProperty(key)) {
  77707. bodyCreationObject[key] = nativeOptions[key];
  77708. }
  77709. }
  77710. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  77711. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  77712. this.world.addEventListener("preStep", impostor.beforeStep);
  77713. this.world.addEventListener("postStep", impostor.afterStep);
  77714. impostor.physicsBody.addShape(shape);
  77715. this.world.add(impostor.physicsBody);
  77716. //try to keep the body moving in the right direction by taking old properties.
  77717. //Should be tested!
  77718. if (oldBody) {
  77719. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  77720. impostor.physicsBody[param].copy(oldBody[param]);
  77721. });
  77722. }
  77723. this._processChildMeshes(impostor);
  77724. }
  77725. //now update the body's transformation
  77726. this._updatePhysicsBodyTransformation(impostor);
  77727. };
  77728. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  77729. var _this = this;
  77730. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  77731. var currentRotation = mainImpostor.object.rotationQuaternion;
  77732. if (meshChildren.length) {
  77733. var processMesh = function (localPosition, mesh) {
  77734. if (!currentRotation || !mesh.rotationQuaternion) {
  77735. return;
  77736. }
  77737. var childImpostor = mesh.getPhysicsImpostor();
  77738. if (childImpostor) {
  77739. var parent = childImpostor.parent;
  77740. if (parent !== mainImpostor) {
  77741. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  77742. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  77743. if (childImpostor.physicsBody) {
  77744. _this.removePhysicsBody(childImpostor);
  77745. childImpostor.physicsBody = null;
  77746. }
  77747. childImpostor.parent = mainImpostor;
  77748. childImpostor.resetUpdateFlags();
  77749. 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));
  77750. //Add the mass of the children.
  77751. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  77752. }
  77753. }
  77754. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  77755. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  77756. };
  77757. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  77758. }
  77759. };
  77760. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  77761. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  77762. this.world.removeEventListener("preStep", impostor.beforeStep);
  77763. this.world.removeEventListener("postStep", impostor.afterStep);
  77764. this.world.remove(impostor.physicsBody);
  77765. };
  77766. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  77767. var mainBody = impostorJoint.mainImpostor.physicsBody;
  77768. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  77769. if (!mainBody || !connectedBody) {
  77770. return;
  77771. }
  77772. var constraint;
  77773. var jointData = impostorJoint.joint.jointData;
  77774. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  77775. var constraintData = {
  77776. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  77777. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  77778. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  77779. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  77780. maxForce: jointData.nativeParams.maxForce,
  77781. collideConnected: !!jointData.collision
  77782. };
  77783. switch (impostorJoint.joint.type) {
  77784. case BABYLON.PhysicsJoint.HingeJoint:
  77785. case BABYLON.PhysicsJoint.Hinge2Joint:
  77786. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  77787. break;
  77788. case BABYLON.PhysicsJoint.DistanceJoint:
  77789. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  77790. break;
  77791. case BABYLON.PhysicsJoint.SpringJoint:
  77792. var springData = jointData;
  77793. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  77794. restLength: springData.length,
  77795. stiffness: springData.stiffness,
  77796. damping: springData.damping,
  77797. localAnchorA: constraintData.pivotA,
  77798. localAnchorB: constraintData.pivotB
  77799. });
  77800. break;
  77801. case BABYLON.PhysicsJoint.LockJoint:
  77802. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  77803. break;
  77804. case BABYLON.PhysicsJoint.PointToPointJoint:
  77805. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  77806. default:
  77807. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  77808. break;
  77809. }
  77810. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  77811. constraint.collideConnected = !!jointData.collision;
  77812. impostorJoint.joint.physicsJoint = constraint;
  77813. //don't add spring as constraint, as it is not one.
  77814. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  77815. this.world.addConstraint(constraint);
  77816. }
  77817. else {
  77818. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  77819. constraint.applyForce();
  77820. });
  77821. }
  77822. };
  77823. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  77824. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  77825. };
  77826. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  77827. var index;
  77828. var mat;
  77829. for (index = 0; index < this._physicsMaterials.length; index++) {
  77830. mat = this._physicsMaterials[index];
  77831. if (mat.friction === friction && mat.restitution === restitution) {
  77832. return mat;
  77833. }
  77834. }
  77835. var currentMat = new this.BJSCANNON.Material(name);
  77836. currentMat.friction = friction;
  77837. currentMat.restitution = restitution;
  77838. this._physicsMaterials.push(currentMat);
  77839. return currentMat;
  77840. };
  77841. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  77842. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  77843. };
  77844. CannonJSPlugin.prototype._createShape = function (impostor) {
  77845. var object = impostor.object;
  77846. var returnValue;
  77847. var extendSize = impostor.getObjectExtendSize();
  77848. switch (impostor.type) {
  77849. case BABYLON.PhysicsImpostor.SphereImpostor:
  77850. var radiusX = extendSize.x;
  77851. var radiusY = extendSize.y;
  77852. var radiusZ = extendSize.z;
  77853. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  77854. break;
  77855. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  77856. case BABYLON.PhysicsImpostor.CylinderImpostor:
  77857. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  77858. break;
  77859. case BABYLON.PhysicsImpostor.BoxImpostor:
  77860. var box = extendSize.scale(0.5);
  77861. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  77862. break;
  77863. case BABYLON.PhysicsImpostor.PlaneImpostor:
  77864. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  77865. returnValue = new this.BJSCANNON.Plane();
  77866. break;
  77867. case BABYLON.PhysicsImpostor.MeshImpostor:
  77868. // should transform the vertex data to world coordinates!!
  77869. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  77870. var rawFaces = object.getIndices ? object.getIndices() : [];
  77871. if (!rawVerts)
  77872. return;
  77873. // get only scale! so the object could transform correctly.
  77874. var oldPosition = object.position.clone();
  77875. var oldRotation = object.rotation && object.rotation.clone();
  77876. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  77877. object.position.copyFromFloats(0, 0, 0);
  77878. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  77879. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  77880. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  77881. var transform = object.computeWorldMatrix(true);
  77882. // convert rawVerts to object space
  77883. var temp = new Array();
  77884. var index;
  77885. for (index = 0; index < rawVerts.length; index += 3) {
  77886. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  77887. }
  77888. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  77889. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  77890. //now set back the transformation!
  77891. object.position.copyFrom(oldPosition);
  77892. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  77893. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  77894. break;
  77895. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  77896. var oldPosition2 = object.position.clone();
  77897. var oldRotation2 = object.rotation && object.rotation.clone();
  77898. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  77899. object.position.copyFromFloats(0, 0, 0);
  77900. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  77901. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  77902. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  77903. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  77904. returnValue = this._createHeightmap(object);
  77905. object.position.copyFrom(oldPosition2);
  77906. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  77907. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  77908. object.computeWorldMatrix(true);
  77909. break;
  77910. case BABYLON.PhysicsImpostor.ParticleImpostor:
  77911. returnValue = new this.BJSCANNON.Particle();
  77912. break;
  77913. }
  77914. return returnValue;
  77915. };
  77916. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  77917. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  77918. var transform = object.computeWorldMatrix(true);
  77919. // convert rawVerts to object space
  77920. var temp = new Array();
  77921. var index;
  77922. for (index = 0; index < pos.length; index += 3) {
  77923. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  77924. }
  77925. pos = temp;
  77926. var matrix = new Array();
  77927. //For now pointDepth will not be used and will be automatically calculated.
  77928. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  77929. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  77930. var boundingInfo = object.getBoundingInfo();
  77931. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  77932. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  77933. var elementSize = dim * 2 / arraySize;
  77934. for (var i = 0; i < pos.length; i = i + 3) {
  77935. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  77936. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  77937. var y = -pos[i + 2] + minY;
  77938. if (!matrix[x]) {
  77939. matrix[x] = [];
  77940. }
  77941. if (!matrix[x][z]) {
  77942. matrix[x][z] = y;
  77943. }
  77944. matrix[x][z] = Math.max(y, matrix[x][z]);
  77945. }
  77946. for (var x = 0; x <= arraySize; ++x) {
  77947. if (!matrix[x]) {
  77948. var loc = 1;
  77949. while (!matrix[(x + loc) % arraySize]) {
  77950. loc++;
  77951. }
  77952. matrix[x] = matrix[(x + loc) % arraySize].slice();
  77953. //console.log("missing x", x);
  77954. }
  77955. for (var z = 0; z <= arraySize; ++z) {
  77956. if (!matrix[x][z]) {
  77957. var loc = 1;
  77958. var newValue;
  77959. while (newValue === undefined) {
  77960. newValue = matrix[x][(z + loc++) % arraySize];
  77961. }
  77962. matrix[x][z] = newValue;
  77963. }
  77964. }
  77965. }
  77966. var shape = new this.BJSCANNON.Heightfield(matrix, {
  77967. elementSize: elementSize
  77968. });
  77969. //For future reference, needed for body transformation
  77970. shape.minY = minY;
  77971. return shape;
  77972. };
  77973. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  77974. var object = impostor.object;
  77975. //make sure it is updated...
  77976. object.computeWorldMatrix && object.computeWorldMatrix(true);
  77977. // The delta between the mesh position and the mesh bounding box center
  77978. var bInfo = object.getBoundingInfo();
  77979. if (!bInfo)
  77980. return;
  77981. var center = impostor.getObjectCenter();
  77982. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  77983. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  77984. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  77985. this._tmpPosition.copyFrom(center);
  77986. var quaternion = object.rotationQuaternion;
  77987. if (!quaternion) {
  77988. return;
  77989. }
  77990. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  77991. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  77992. //-90 DEG in X, precalculated
  77993. quaternion = quaternion.multiply(this._minus90X);
  77994. //Invert! (Precalculated, 90 deg in X)
  77995. //No need to clone. this will never change.
  77996. impostor.setDeltaRotation(this._plus90X);
  77997. }
  77998. //If it is a heightfield, if should be centered.
  77999. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  78000. var mesh = object;
  78001. var boundingInfo = mesh.getBoundingInfo();
  78002. //calculate the correct body position:
  78003. var rotationQuaternion = mesh.rotationQuaternion;
  78004. mesh.rotationQuaternion = this._tmpUnityRotation;
  78005. mesh.computeWorldMatrix(true);
  78006. //get original center with no rotation
  78007. var c = center.clone();
  78008. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  78009. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  78010. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  78011. mesh.setPreTransformMatrix(p);
  78012. mesh.computeWorldMatrix(true);
  78013. //calculate the translation
  78014. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  78015. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  78016. //add it inverted to the delta
  78017. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  78018. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  78019. //rotation is back
  78020. mesh.rotationQuaternion = rotationQuaternion;
  78021. mesh.setPreTransformMatrix(oldPivot);
  78022. mesh.computeWorldMatrix(true);
  78023. }
  78024. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  78025. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  78026. //this._tmpPosition.copyFrom(object.position);
  78027. }
  78028. impostor.setDeltaPosition(this._tmpDeltaPosition);
  78029. //Now update the impostor object
  78030. impostor.physicsBody.position.copy(this._tmpPosition);
  78031. impostor.physicsBody.quaternion.copy(quaternion);
  78032. };
  78033. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  78034. impostor.object.position.copyFrom(impostor.physicsBody.position);
  78035. if (impostor.object.rotationQuaternion) {
  78036. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  78037. }
  78038. };
  78039. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  78040. impostor.physicsBody.position.copy(newPosition);
  78041. impostor.physicsBody.quaternion.copy(newRotation);
  78042. };
  78043. CannonJSPlugin.prototype.isSupported = function () {
  78044. return this.BJSCANNON !== undefined;
  78045. };
  78046. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  78047. impostor.physicsBody.velocity.copy(velocity);
  78048. };
  78049. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  78050. impostor.physicsBody.angularVelocity.copy(velocity);
  78051. };
  78052. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  78053. var v = impostor.physicsBody.velocity;
  78054. if (!v) {
  78055. return null;
  78056. }
  78057. return new BABYLON.Vector3(v.x, v.y, v.z);
  78058. };
  78059. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  78060. var v = impostor.physicsBody.angularVelocity;
  78061. if (!v) {
  78062. return null;
  78063. }
  78064. return new BABYLON.Vector3(v.x, v.y, v.z);
  78065. };
  78066. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  78067. impostor.physicsBody.mass = mass;
  78068. impostor.physicsBody.updateMassProperties();
  78069. };
  78070. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  78071. return impostor.physicsBody.mass;
  78072. };
  78073. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  78074. return impostor.physicsBody.material.friction;
  78075. };
  78076. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  78077. impostor.physicsBody.material.friction = friction;
  78078. };
  78079. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  78080. return impostor.physicsBody.material.restitution;
  78081. };
  78082. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  78083. impostor.physicsBody.material.restitution = restitution;
  78084. };
  78085. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  78086. impostor.physicsBody.sleep();
  78087. };
  78088. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  78089. impostor.physicsBody.wakeUp();
  78090. };
  78091. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  78092. joint.physicsJoint.distance = maxDistance;
  78093. };
  78094. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  78095. // if (!motorIndex) {
  78096. // joint.physicsJoint.enableMotor();
  78097. // }
  78098. // }
  78099. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  78100. // if (!motorIndex) {
  78101. // joint.physicsJoint.disableMotor();
  78102. // }
  78103. // }
  78104. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  78105. if (!motorIndex) {
  78106. joint.physicsJoint.enableMotor();
  78107. joint.physicsJoint.setMotorSpeed(speed);
  78108. if (maxForce) {
  78109. this.setLimit(joint, maxForce);
  78110. }
  78111. }
  78112. };
  78113. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  78114. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  78115. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  78116. };
  78117. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  78118. var body = impostor.physicsBody;
  78119. mesh.position.x = body.position.x;
  78120. mesh.position.y = body.position.y;
  78121. mesh.position.z = body.position.z;
  78122. if (mesh.rotationQuaternion) {
  78123. mesh.rotationQuaternion.x = body.quaternion.x;
  78124. mesh.rotationQuaternion.y = body.quaternion.y;
  78125. mesh.rotationQuaternion.z = body.quaternion.z;
  78126. mesh.rotationQuaternion.w = body.quaternion.w;
  78127. }
  78128. };
  78129. CannonJSPlugin.prototype.getRadius = function (impostor) {
  78130. var shape = impostor.physicsBody.shapes[0];
  78131. return shape.boundingSphereRadius;
  78132. };
  78133. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  78134. var shape = impostor.physicsBody.shapes[0];
  78135. result.x = shape.halfExtents.x * 2;
  78136. result.y = shape.halfExtents.y * 2;
  78137. result.z = shape.halfExtents.z * 2;
  78138. };
  78139. CannonJSPlugin.prototype.dispose = function () {
  78140. };
  78141. CannonJSPlugin.prototype._extendNamespace = function () {
  78142. //this will force cannon to execute at least one step when using interpolation
  78143. var step_tmp1 = new this.BJSCANNON.Vec3();
  78144. var Engine = this.BJSCANNON;
  78145. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  78146. maxSubSteps = maxSubSteps || 10;
  78147. timeSinceLastCalled = timeSinceLastCalled || 0;
  78148. if (timeSinceLastCalled === 0) {
  78149. this.internalStep(dt);
  78150. this.time += dt;
  78151. }
  78152. else {
  78153. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  78154. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  78155. var t0 = performance.now();
  78156. for (var i = 0; i !== internalSteps; i++) {
  78157. this.internalStep(dt);
  78158. if (performance.now() - t0 > dt * 1000) {
  78159. break;
  78160. }
  78161. }
  78162. this.time += timeSinceLastCalled;
  78163. var h = this.time % dt;
  78164. var h_div_dt = h / dt;
  78165. var interpvelo = step_tmp1;
  78166. var bodies = this.bodies;
  78167. for (var j = 0; j !== bodies.length; j++) {
  78168. var b = bodies[j];
  78169. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  78170. b.position.vsub(b.previousPosition, interpvelo);
  78171. interpvelo.scale(h_div_dt, interpvelo);
  78172. b.position.vadd(interpvelo, b.interpolatedPosition);
  78173. }
  78174. else {
  78175. b.interpolatedPosition.copy(b.position);
  78176. b.interpolatedQuaternion.copy(b.quaternion);
  78177. }
  78178. }
  78179. }
  78180. };
  78181. };
  78182. return CannonJSPlugin;
  78183. }());
  78184. BABYLON.CannonJSPlugin = CannonJSPlugin;
  78185. })(BABYLON || (BABYLON = {}));
  78186. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  78187. "use strict";
  78188. var BABYLON;
  78189. (function (BABYLON) {
  78190. var OimoJSPlugin = /** @class */ (function () {
  78191. function OimoJSPlugin(iterations) {
  78192. this.name = "OimoJSPlugin";
  78193. this._tmpImpostorsArray = [];
  78194. this._tmpPositionVector = BABYLON.Vector3.Zero();
  78195. this.BJSOIMO = OIMO;
  78196. this.world = new this.BJSOIMO.World({
  78197. iterations: iterations
  78198. });
  78199. this.world.clear();
  78200. }
  78201. OimoJSPlugin.prototype.setGravity = function (gravity) {
  78202. this.world.gravity.copy(gravity);
  78203. };
  78204. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  78205. this.world.timeStep = timeStep;
  78206. };
  78207. OimoJSPlugin.prototype.getTimeStep = function () {
  78208. return this.world.timeStep;
  78209. };
  78210. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  78211. var _this = this;
  78212. impostors.forEach(function (impostor) {
  78213. impostor.beforeStep();
  78214. });
  78215. this.world.step();
  78216. impostors.forEach(function (impostor) {
  78217. impostor.afterStep();
  78218. //update the ordered impostors array
  78219. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  78220. });
  78221. //check for collisions
  78222. var contact = this.world.contacts;
  78223. while (contact !== null) {
  78224. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  78225. contact = contact.next;
  78226. continue;
  78227. }
  78228. //is this body colliding with any other? get the impostor
  78229. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  78230. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  78231. if (!mainImpostor || !collidingImpostor) {
  78232. contact = contact.next;
  78233. continue;
  78234. }
  78235. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  78236. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  78237. contact = contact.next;
  78238. }
  78239. };
  78240. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  78241. var mass = impostor.physicsBody.mass;
  78242. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  78243. };
  78244. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  78245. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  78246. this.applyImpulse(impostor, force, contactPoint);
  78247. };
  78248. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  78249. var _this = this;
  78250. //parent-child relationship. Does this impostor has a parent impostor?
  78251. if (impostor.parent) {
  78252. if (impostor.physicsBody) {
  78253. this.removePhysicsBody(impostor);
  78254. //TODO is that needed?
  78255. impostor.forceUpdate();
  78256. }
  78257. return;
  78258. }
  78259. if (impostor.isBodyInitRequired()) {
  78260. var bodyConfig = {
  78261. name: impostor.uniqueId,
  78262. //Oimo must have mass, also for static objects.
  78263. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  78264. size: [],
  78265. type: [],
  78266. pos: [],
  78267. posShape: [],
  78268. rot: [],
  78269. rotShape: [],
  78270. move: impostor.getParam("mass") !== 0,
  78271. density: impostor.getParam("mass"),
  78272. friction: impostor.getParam("friction"),
  78273. restitution: impostor.getParam("restitution"),
  78274. //Supporting older versions of Oimo
  78275. world: this.world
  78276. };
  78277. var impostors = [impostor];
  78278. var addToArray = function (parent) {
  78279. if (!parent.getChildMeshes)
  78280. return;
  78281. parent.getChildMeshes().forEach(function (m) {
  78282. if (m.physicsImpostor) {
  78283. impostors.push(m.physicsImpostor);
  78284. //m.physicsImpostor._init();
  78285. }
  78286. });
  78287. };
  78288. addToArray(impostor.object);
  78289. var checkWithEpsilon_1 = function (value) {
  78290. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  78291. };
  78292. impostors.forEach(function (i) {
  78293. if (!i.object.rotationQuaternion) {
  78294. return;
  78295. }
  78296. //get the correct bounding box
  78297. var oldQuaternion = i.object.rotationQuaternion;
  78298. var rot = oldQuaternion.toEulerAngles();
  78299. var extendSize = i.getObjectExtendSize();
  78300. var radToDeg = 57.295779513082320876;
  78301. if (i === impostor) {
  78302. var center = impostor.getObjectCenter();
  78303. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  78304. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  78305. //Can also use Array.prototype.push.apply
  78306. bodyConfig.pos.push(center.x);
  78307. bodyConfig.pos.push(center.y);
  78308. bodyConfig.pos.push(center.z);
  78309. bodyConfig.posShape.push(0, 0, 0);
  78310. //tmp solution
  78311. bodyConfig.rot.push(rot.x * radToDeg);
  78312. bodyConfig.rot.push(rot.y * radToDeg);
  78313. bodyConfig.rot.push(rot.z * radToDeg);
  78314. bodyConfig.rotShape.push(0, 0, 0);
  78315. }
  78316. else {
  78317. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  78318. bodyConfig.posShape.push(localPosition.x);
  78319. bodyConfig.posShape.push(localPosition.y);
  78320. bodyConfig.posShape.push(localPosition.z);
  78321. bodyConfig.pos.push(0, 0, 0);
  78322. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  78323. bodyConfig.rot.push(0);
  78324. bodyConfig.rot.push(0);
  78325. bodyConfig.rot.push(0);
  78326. bodyConfig.rotShape.push(rot.x * radToDeg);
  78327. bodyConfig.rotShape.push(rot.y * radToDeg);
  78328. bodyConfig.rotShape.push(rot.z * radToDeg);
  78329. }
  78330. // register mesh
  78331. switch (i.type) {
  78332. case BABYLON.PhysicsImpostor.ParticleImpostor:
  78333. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  78334. case BABYLON.PhysicsImpostor.SphereImpostor:
  78335. var radiusX = extendSize.x;
  78336. var radiusY = extendSize.y;
  78337. var radiusZ = extendSize.z;
  78338. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  78339. bodyConfig.type.push('sphere');
  78340. //due to the way oimo works with compounds, add 3 times
  78341. bodyConfig.size.push(size);
  78342. bodyConfig.size.push(size);
  78343. bodyConfig.size.push(size);
  78344. break;
  78345. case BABYLON.PhysicsImpostor.CylinderImpostor:
  78346. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  78347. var sizeY = checkWithEpsilon_1(extendSize.y);
  78348. bodyConfig.type.push('cylinder');
  78349. bodyConfig.size.push(sizeX);
  78350. bodyConfig.size.push(sizeY);
  78351. //due to the way oimo works with compounds, add one more value.
  78352. bodyConfig.size.push(sizeY);
  78353. break;
  78354. case BABYLON.PhysicsImpostor.PlaneImpostor:
  78355. case BABYLON.PhysicsImpostor.BoxImpostor:
  78356. default:
  78357. var sizeX = checkWithEpsilon_1(extendSize.x);
  78358. var sizeY = checkWithEpsilon_1(extendSize.y);
  78359. var sizeZ = checkWithEpsilon_1(extendSize.z);
  78360. bodyConfig.type.push('box');
  78361. //if (i === impostor) {
  78362. bodyConfig.size.push(sizeX);
  78363. bodyConfig.size.push(sizeY);
  78364. bodyConfig.size.push(sizeZ);
  78365. //} else {
  78366. // bodyConfig.size.push(0,0,0);
  78367. //}
  78368. break;
  78369. }
  78370. //actually not needed, but hey...
  78371. i.object.rotationQuaternion = oldQuaternion;
  78372. });
  78373. impostor.physicsBody = this.world.add(bodyConfig);
  78374. }
  78375. else {
  78376. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  78377. }
  78378. impostor.setDeltaPosition(this._tmpPositionVector);
  78379. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  78380. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  78381. };
  78382. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  78383. //impostor.physicsBody.dispose();
  78384. //Same as : (older oimo versions)
  78385. this.world.removeRigidBody(impostor.physicsBody);
  78386. };
  78387. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  78388. var mainBody = impostorJoint.mainImpostor.physicsBody;
  78389. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  78390. if (!mainBody || !connectedBody) {
  78391. return;
  78392. }
  78393. var jointData = impostorJoint.joint.jointData;
  78394. var options = jointData.nativeParams || {};
  78395. var type;
  78396. var nativeJointData = {
  78397. body1: mainBody,
  78398. body2: connectedBody,
  78399. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  78400. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  78401. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  78402. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  78403. min: options.min,
  78404. max: options.max,
  78405. collision: options.collision || jointData.collision,
  78406. spring: options.spring,
  78407. //supporting older version of Oimo
  78408. world: this.world
  78409. };
  78410. switch (impostorJoint.joint.type) {
  78411. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  78412. type = "jointBall";
  78413. break;
  78414. case BABYLON.PhysicsJoint.SpringJoint:
  78415. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  78416. var springData = jointData;
  78417. nativeJointData.min = springData.length || nativeJointData.min;
  78418. //Max should also be set, just make sure it is at least min
  78419. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  78420. case BABYLON.PhysicsJoint.DistanceJoint:
  78421. type = "jointDistance";
  78422. nativeJointData.max = jointData.maxDistance;
  78423. break;
  78424. case BABYLON.PhysicsJoint.PrismaticJoint:
  78425. type = "jointPrisme";
  78426. break;
  78427. case BABYLON.PhysicsJoint.SliderJoint:
  78428. type = "jointSlide";
  78429. break;
  78430. case BABYLON.PhysicsJoint.WheelJoint:
  78431. type = "jointWheel";
  78432. break;
  78433. case BABYLON.PhysicsJoint.HingeJoint:
  78434. default:
  78435. type = "jointHinge";
  78436. break;
  78437. }
  78438. nativeJointData.type = type;
  78439. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  78440. };
  78441. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  78442. //Bug in Oimo prevents us from disposing a joint in the playground
  78443. //joint.joint.physicsJoint.dispose();
  78444. //So we will bruteforce it!
  78445. try {
  78446. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  78447. }
  78448. catch (e) {
  78449. BABYLON.Tools.Warn(e);
  78450. }
  78451. };
  78452. OimoJSPlugin.prototype.isSupported = function () {
  78453. return this.BJSOIMO !== undefined;
  78454. };
  78455. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  78456. if (!impostor.physicsBody.sleeping) {
  78457. //TODO check that
  78458. /*if (impostor.physicsBody.shapes.next) {
  78459. var parentShape = this._getLastShape(impostor.physicsBody);
  78460. impostor.object.position.copyFrom(parentShape.position);
  78461. console.log(parentShape.position);
  78462. } else {*/
  78463. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  78464. //}
  78465. if (impostor.object.rotationQuaternion) {
  78466. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  78467. }
  78468. }
  78469. };
  78470. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  78471. var body = impostor.physicsBody;
  78472. body.position.copy(newPosition);
  78473. body.orientation.copy(newRotation);
  78474. body.syncShapes();
  78475. body.awake();
  78476. };
  78477. /*private _getLastShape(body: any): any {
  78478. var lastShape = body.shapes;
  78479. while (lastShape.next) {
  78480. lastShape = lastShape.next;
  78481. }
  78482. return lastShape;
  78483. }*/
  78484. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  78485. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  78486. };
  78487. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  78488. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  78489. };
  78490. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  78491. var v = impostor.physicsBody.linearVelocity;
  78492. if (!v) {
  78493. return null;
  78494. }
  78495. return new BABYLON.Vector3(v.x, v.y, v.z);
  78496. };
  78497. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  78498. var v = impostor.physicsBody.angularVelocity;
  78499. if (!v) {
  78500. return null;
  78501. }
  78502. return new BABYLON.Vector3(v.x, v.y, v.z);
  78503. };
  78504. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  78505. var staticBody = mass === 0;
  78506. //this will actually set the body's density and not its mass.
  78507. //But this is how oimo treats the mass variable.
  78508. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  78509. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  78510. };
  78511. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  78512. return impostor.physicsBody.shapes.density;
  78513. };
  78514. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  78515. return impostor.physicsBody.shapes.friction;
  78516. };
  78517. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  78518. impostor.physicsBody.shapes.friction = friction;
  78519. };
  78520. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  78521. return impostor.physicsBody.shapes.restitution;
  78522. };
  78523. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  78524. impostor.physicsBody.shapes.restitution = restitution;
  78525. };
  78526. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  78527. impostor.physicsBody.sleep();
  78528. };
  78529. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  78530. impostor.physicsBody.awake();
  78531. };
  78532. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  78533. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  78534. if (minDistance !== void 0) {
  78535. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  78536. }
  78537. };
  78538. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  78539. //TODO separate rotational and transational motors.
  78540. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  78541. if (motor) {
  78542. motor.setMotor(speed, maxForce);
  78543. }
  78544. };
  78545. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  78546. //TODO separate rotational and transational motors.
  78547. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  78548. if (motor) {
  78549. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  78550. }
  78551. };
  78552. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  78553. var body = impostor.physicsBody;
  78554. mesh.position.x = body.position.x;
  78555. mesh.position.y = body.position.y;
  78556. mesh.position.z = body.position.z;
  78557. if (mesh.rotationQuaternion) {
  78558. mesh.rotationQuaternion.x = body.orientation.x;
  78559. mesh.rotationQuaternion.y = body.orientation.y;
  78560. mesh.rotationQuaternion.z = body.orientation.z;
  78561. mesh.rotationQuaternion.w = body.orientation.s;
  78562. }
  78563. };
  78564. OimoJSPlugin.prototype.getRadius = function (impostor) {
  78565. return impostor.physicsBody.shapes.radius;
  78566. };
  78567. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  78568. var shape = impostor.physicsBody.shapes;
  78569. result.x = shape.halfWidth * 2;
  78570. result.y = shape.halfHeight * 2;
  78571. result.z = shape.halfDepth * 2;
  78572. };
  78573. OimoJSPlugin.prototype.dispose = function () {
  78574. this.world.clear();
  78575. };
  78576. return OimoJSPlugin;
  78577. }());
  78578. BABYLON.OimoJSPlugin = OimoJSPlugin;
  78579. })(BABYLON || (BABYLON = {}));
  78580. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  78581. "use strict";
  78582. var BABYLON;
  78583. (function (BABYLON) {
  78584. /*
  78585. * Based on jsTGALoader - Javascript loader for TGA file
  78586. * By Vincent Thibault
  78587. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  78588. */
  78589. var TGATools = /** @class */ (function () {
  78590. function TGATools() {
  78591. }
  78592. TGATools.GetTGAHeader = function (data) {
  78593. var offset = 0;
  78594. var header = {
  78595. id_length: data[offset++],
  78596. colormap_type: data[offset++],
  78597. image_type: data[offset++],
  78598. colormap_index: data[offset++] | data[offset++] << 8,
  78599. colormap_length: data[offset++] | data[offset++] << 8,
  78600. colormap_size: data[offset++],
  78601. origin: [
  78602. data[offset++] | data[offset++] << 8,
  78603. data[offset++] | data[offset++] << 8
  78604. ],
  78605. width: data[offset++] | data[offset++] << 8,
  78606. height: data[offset++] | data[offset++] << 8,
  78607. pixel_size: data[offset++],
  78608. flags: data[offset++]
  78609. };
  78610. return header;
  78611. };
  78612. TGATools.UploadContent = function (gl, data) {
  78613. // Not enough data to contain header ?
  78614. if (data.length < 19) {
  78615. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  78616. return;
  78617. }
  78618. // Read Header
  78619. var offset = 18;
  78620. var header = TGATools.GetTGAHeader(data);
  78621. // Assume it's a valid Targa file.
  78622. if (header.id_length + offset > data.length) {
  78623. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  78624. return;
  78625. }
  78626. // Skip not needed data
  78627. offset += header.id_length;
  78628. var use_rle = false;
  78629. var use_pal = false;
  78630. var use_grey = false;
  78631. // Get some informations.
  78632. switch (header.image_type) {
  78633. case TGATools._TYPE_RLE_INDEXED:
  78634. use_rle = true;
  78635. case TGATools._TYPE_INDEXED:
  78636. use_pal = true;
  78637. break;
  78638. case TGATools._TYPE_RLE_RGB:
  78639. use_rle = true;
  78640. case TGATools._TYPE_RGB:
  78641. // use_rgb = true;
  78642. break;
  78643. case TGATools._TYPE_RLE_GREY:
  78644. use_rle = true;
  78645. case TGATools._TYPE_GREY:
  78646. use_grey = true;
  78647. break;
  78648. }
  78649. var pixel_data;
  78650. // var numAlphaBits = header.flags & 0xf;
  78651. var pixel_size = header.pixel_size >> 3;
  78652. var pixel_total = header.width * header.height * pixel_size;
  78653. // Read palettes
  78654. var palettes;
  78655. if (use_pal) {
  78656. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  78657. }
  78658. // Read LRE
  78659. if (use_rle) {
  78660. pixel_data = new Uint8Array(pixel_total);
  78661. var c, count, i;
  78662. var localOffset = 0;
  78663. var pixels = new Uint8Array(pixel_size);
  78664. while (offset < pixel_total && localOffset < pixel_total) {
  78665. c = data[offset++];
  78666. count = (c & 0x7f) + 1;
  78667. // RLE pixels
  78668. if (c & 0x80) {
  78669. // Bind pixel tmp array
  78670. for (i = 0; i < pixel_size; ++i) {
  78671. pixels[i] = data[offset++];
  78672. }
  78673. // Copy pixel array
  78674. for (i = 0; i < count; ++i) {
  78675. pixel_data.set(pixels, localOffset + i * pixel_size);
  78676. }
  78677. localOffset += pixel_size * count;
  78678. }
  78679. else {
  78680. count *= pixel_size;
  78681. for (i = 0; i < count; ++i) {
  78682. pixel_data[localOffset + i] = data[offset++];
  78683. }
  78684. localOffset += count;
  78685. }
  78686. }
  78687. }
  78688. else {
  78689. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  78690. }
  78691. // Load to texture
  78692. var x_start, y_start, x_step, y_step, y_end, x_end;
  78693. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  78694. default:
  78695. case TGATools._ORIGIN_UL:
  78696. x_start = 0;
  78697. x_step = 1;
  78698. x_end = header.width;
  78699. y_start = 0;
  78700. y_step = 1;
  78701. y_end = header.height;
  78702. break;
  78703. case TGATools._ORIGIN_BL:
  78704. x_start = 0;
  78705. x_step = 1;
  78706. x_end = header.width;
  78707. y_start = header.height - 1;
  78708. y_step = -1;
  78709. y_end = -1;
  78710. break;
  78711. case TGATools._ORIGIN_UR:
  78712. x_start = header.width - 1;
  78713. x_step = -1;
  78714. x_end = -1;
  78715. y_start = 0;
  78716. y_step = 1;
  78717. y_end = header.height;
  78718. break;
  78719. case TGATools._ORIGIN_BR:
  78720. x_start = header.width - 1;
  78721. x_step = -1;
  78722. x_end = -1;
  78723. y_start = header.height - 1;
  78724. y_step = -1;
  78725. y_end = -1;
  78726. break;
  78727. }
  78728. // Load the specify method
  78729. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  78730. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  78731. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  78732. };
  78733. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78734. var image = pixel_data, colormap = palettes;
  78735. var width = header.width, height = header.height;
  78736. var color, i = 0, x, y;
  78737. var imageData = new Uint8Array(width * height * 4);
  78738. for (y = y_start; y !== y_end; y += y_step) {
  78739. for (x = x_start; x !== x_end; x += x_step, i++) {
  78740. color = image[i];
  78741. imageData[(x + width * y) * 4 + 3] = 255;
  78742. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  78743. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  78744. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  78745. }
  78746. }
  78747. return imageData;
  78748. };
  78749. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78750. var image = pixel_data;
  78751. var width = header.width, height = header.height;
  78752. var color, i = 0, x, y;
  78753. var imageData = new Uint8Array(width * height * 4);
  78754. for (y = y_start; y !== y_end; y += y_step) {
  78755. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  78756. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  78757. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  78758. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  78759. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  78760. imageData[(x + width * y) * 4 + 0] = r;
  78761. imageData[(x + width * y) * 4 + 1] = g;
  78762. imageData[(x + width * y) * 4 + 2] = b;
  78763. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  78764. }
  78765. }
  78766. return imageData;
  78767. };
  78768. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78769. var image = pixel_data;
  78770. var width = header.width, height = header.height;
  78771. var i = 0, x, y;
  78772. var imageData = new Uint8Array(width * height * 4);
  78773. for (y = y_start; y !== y_end; y += y_step) {
  78774. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  78775. imageData[(x + width * y) * 4 + 3] = 255;
  78776. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  78777. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  78778. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  78779. }
  78780. }
  78781. return imageData;
  78782. };
  78783. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78784. var image = pixel_data;
  78785. var width = header.width, height = header.height;
  78786. var i = 0, x, y;
  78787. var imageData = new Uint8Array(width * height * 4);
  78788. for (y = y_start; y !== y_end; y += y_step) {
  78789. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  78790. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  78791. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  78792. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  78793. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  78794. }
  78795. }
  78796. return imageData;
  78797. };
  78798. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78799. var image = pixel_data;
  78800. var width = header.width, height = header.height;
  78801. var color, i = 0, x, y;
  78802. var imageData = new Uint8Array(width * height * 4);
  78803. for (y = y_start; y !== y_end; y += y_step) {
  78804. for (x = x_start; x !== x_end; x += x_step, i++) {
  78805. color = image[i];
  78806. imageData[(x + width * y) * 4 + 0] = color;
  78807. imageData[(x + width * y) * 4 + 1] = color;
  78808. imageData[(x + width * y) * 4 + 2] = color;
  78809. imageData[(x + width * y) * 4 + 3] = 255;
  78810. }
  78811. }
  78812. return imageData;
  78813. };
  78814. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78815. var image = pixel_data;
  78816. var width = header.width, height = header.height;
  78817. var i = 0, x, y;
  78818. var imageData = new Uint8Array(width * height * 4);
  78819. for (y = y_start; y !== y_end; y += y_step) {
  78820. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  78821. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  78822. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  78823. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  78824. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  78825. }
  78826. }
  78827. return imageData;
  78828. };
  78829. //private static _TYPE_NO_DATA = 0;
  78830. TGATools._TYPE_INDEXED = 1;
  78831. TGATools._TYPE_RGB = 2;
  78832. TGATools._TYPE_GREY = 3;
  78833. TGATools._TYPE_RLE_INDEXED = 9;
  78834. TGATools._TYPE_RLE_RGB = 10;
  78835. TGATools._TYPE_RLE_GREY = 11;
  78836. TGATools._ORIGIN_MASK = 0x30;
  78837. TGATools._ORIGIN_SHIFT = 0x04;
  78838. TGATools._ORIGIN_BL = 0x00;
  78839. TGATools._ORIGIN_BR = 0x01;
  78840. TGATools._ORIGIN_UL = 0x02;
  78841. TGATools._ORIGIN_UR = 0x03;
  78842. return TGATools;
  78843. }());
  78844. BABYLON.TGATools = TGATools;
  78845. })(BABYLON || (BABYLON = {}));
  78846. //# sourceMappingURL=babylon.tga.js.map
  78847. "use strict";
  78848. var BABYLON;
  78849. (function (BABYLON) {
  78850. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  78851. // All values and structures referenced from:
  78852. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  78853. var DDS_MAGIC = 0x20534444;
  78854. var
  78855. //DDSD_CAPS = 0x1,
  78856. //DDSD_HEIGHT = 0x2,
  78857. //DDSD_WIDTH = 0x4,
  78858. //DDSD_PITCH = 0x8,
  78859. //DDSD_PIXELFORMAT = 0x1000,
  78860. DDSD_MIPMAPCOUNT = 0x20000;
  78861. //DDSD_LINEARSIZE = 0x80000,
  78862. //DDSD_DEPTH = 0x800000;
  78863. // var DDSCAPS_COMPLEX = 0x8,
  78864. // DDSCAPS_MIPMAP = 0x400000,
  78865. // DDSCAPS_TEXTURE = 0x1000;
  78866. var DDSCAPS2_CUBEMAP = 0x200;
  78867. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  78868. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  78869. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  78870. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  78871. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  78872. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  78873. // DDSCAPS2_VOLUME = 0x200000;
  78874. var
  78875. //DDPF_ALPHAPIXELS = 0x1,
  78876. //DDPF_ALPHA = 0x2,
  78877. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  78878. //DDPF_YUV = 0x200,
  78879. DDPF_LUMINANCE = 0x20000;
  78880. function FourCCToInt32(value) {
  78881. return value.charCodeAt(0) +
  78882. (value.charCodeAt(1) << 8) +
  78883. (value.charCodeAt(2) << 16) +
  78884. (value.charCodeAt(3) << 24);
  78885. }
  78886. function Int32ToFourCC(value) {
  78887. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  78888. }
  78889. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  78890. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  78891. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  78892. var FOURCC_DX10 = FourCCToInt32("DX10");
  78893. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  78894. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  78895. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  78896. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  78897. var headerLengthInt = 31; // The header length in 32 bit ints
  78898. // Offsets into the header array
  78899. var off_magic = 0;
  78900. var off_size = 1;
  78901. var off_flags = 2;
  78902. var off_height = 3;
  78903. var off_width = 4;
  78904. var off_mipmapCount = 7;
  78905. var off_pfFlags = 20;
  78906. var off_pfFourCC = 21;
  78907. var off_RGBbpp = 22;
  78908. var off_RMask = 23;
  78909. var off_GMask = 24;
  78910. var off_BMask = 25;
  78911. var off_AMask = 26;
  78912. // var off_caps1 = 27;
  78913. var off_caps2 = 28;
  78914. // var off_caps3 = 29;
  78915. // var off_caps4 = 30;
  78916. var off_dxgiFormat = 32;
  78917. ;
  78918. var DDSTools = /** @class */ (function () {
  78919. function DDSTools() {
  78920. }
  78921. DDSTools.GetDDSInfo = function (arrayBuffer) {
  78922. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  78923. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  78924. var mipmapCount = 1;
  78925. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  78926. mipmapCount = Math.max(1, header[off_mipmapCount]);
  78927. }
  78928. var fourCC = header[off_pfFourCC];
  78929. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  78930. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  78931. switch (fourCC) {
  78932. case FOURCC_D3DFMT_R16G16B16A16F:
  78933. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78934. break;
  78935. case FOURCC_D3DFMT_R32G32B32A32F:
  78936. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78937. break;
  78938. case FOURCC_DX10:
  78939. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  78940. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78941. break;
  78942. }
  78943. }
  78944. return {
  78945. width: header[off_width],
  78946. height: header[off_height],
  78947. mipmapCount: mipmapCount,
  78948. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  78949. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  78950. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  78951. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  78952. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  78953. dxgiFormat: dxgiFormat,
  78954. textureType: textureType
  78955. };
  78956. };
  78957. DDSTools._ToHalfFloat = function (value) {
  78958. if (!DDSTools._FloatView) {
  78959. DDSTools._FloatView = new Float32Array(1);
  78960. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  78961. }
  78962. DDSTools._FloatView[0] = value;
  78963. var x = DDSTools._Int32View[0];
  78964. var bits = (x >> 16) & 0x8000; /* Get the sign */
  78965. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  78966. var e = (x >> 23) & 0xff; /* Using int is faster here */
  78967. /* If zero, or denormal, or exponent underflows too much for a denormal
  78968. * half, return signed zero. */
  78969. if (e < 103) {
  78970. return bits;
  78971. }
  78972. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  78973. if (e > 142) {
  78974. bits |= 0x7c00;
  78975. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  78976. * not Inf, so make sure we set one mantissa bit too. */
  78977. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  78978. return bits;
  78979. }
  78980. /* If exponent underflows but not too much, return a denormal */
  78981. if (e < 113) {
  78982. m |= 0x0800;
  78983. /* Extra rounding may overflow and set mantissa to 0 and exponent
  78984. * to 1, which is OK. */
  78985. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  78986. return bits;
  78987. }
  78988. bits |= ((e - 112) << 10) | (m >> 1);
  78989. bits += m & 1;
  78990. return bits;
  78991. };
  78992. DDSTools._FromHalfFloat = function (value) {
  78993. var s = (value & 0x8000) >> 15;
  78994. var e = (value & 0x7C00) >> 10;
  78995. var f = value & 0x03FF;
  78996. if (e === 0) {
  78997. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  78998. }
  78999. else if (e == 0x1F) {
  79000. return f ? NaN : ((s ? -1 : 1) * Infinity);
  79001. }
  79002. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  79003. };
  79004. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79005. var destArray = new Float32Array(dataLength);
  79006. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79007. var index = 0;
  79008. for (var y = 0; y < height; y++) {
  79009. for (var x = 0; x < width; x++) {
  79010. var srcPos = (x + y * width) * 4;
  79011. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  79012. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  79013. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  79014. if (DDSTools.StoreLODInAlphaChannel) {
  79015. destArray[index + 3] = lod;
  79016. }
  79017. else {
  79018. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  79019. }
  79020. index += 4;
  79021. }
  79022. }
  79023. return destArray;
  79024. };
  79025. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79026. if (DDSTools.StoreLODInAlphaChannel) {
  79027. var destArray = new Uint16Array(dataLength);
  79028. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79029. var index = 0;
  79030. for (var y = 0; y < height; y++) {
  79031. for (var x = 0; x < width; x++) {
  79032. var srcPos = (x + y * width) * 4;
  79033. destArray[index] = srcData[srcPos];
  79034. destArray[index + 1] = srcData[srcPos + 1];
  79035. destArray[index + 2] = srcData[srcPos + 2];
  79036. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  79037. index += 4;
  79038. }
  79039. }
  79040. return destArray;
  79041. }
  79042. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  79043. };
  79044. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79045. if (DDSTools.StoreLODInAlphaChannel) {
  79046. var destArray = new Float32Array(dataLength);
  79047. var srcData = new Float32Array(arrayBuffer, dataOffset);
  79048. var index = 0;
  79049. for (var y = 0; y < height; y++) {
  79050. for (var x = 0; x < width; x++) {
  79051. var srcPos = (x + y * width) * 4;
  79052. destArray[index] = srcData[srcPos];
  79053. destArray[index + 1] = srcData[srcPos + 1];
  79054. destArray[index + 2] = srcData[srcPos + 2];
  79055. destArray[index + 3] = lod;
  79056. index += 4;
  79057. }
  79058. }
  79059. return destArray;
  79060. }
  79061. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  79062. };
  79063. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79064. var destArray = new Uint8Array(dataLength);
  79065. var srcData = new Float32Array(arrayBuffer, dataOffset);
  79066. var index = 0;
  79067. for (var y = 0; y < height; y++) {
  79068. for (var x = 0; x < width; x++) {
  79069. var srcPos = (x + y * width) * 4;
  79070. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  79071. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  79072. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  79073. if (DDSTools.StoreLODInAlphaChannel) {
  79074. destArray[index + 3] = lod;
  79075. }
  79076. else {
  79077. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  79078. }
  79079. index += 4;
  79080. }
  79081. }
  79082. return destArray;
  79083. };
  79084. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79085. var destArray = new Uint8Array(dataLength);
  79086. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79087. var index = 0;
  79088. for (var y = 0; y < height; y++) {
  79089. for (var x = 0; x < width; x++) {
  79090. var srcPos = (x + y * width) * 4;
  79091. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  79092. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  79093. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  79094. if (DDSTools.StoreLODInAlphaChannel) {
  79095. destArray[index + 3] = lod;
  79096. }
  79097. else {
  79098. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  79099. }
  79100. index += 4;
  79101. }
  79102. }
  79103. return destArray;
  79104. };
  79105. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  79106. var byteArray = new Uint8Array(dataLength);
  79107. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79108. var index = 0;
  79109. for (var y = 0; y < height; y++) {
  79110. for (var x = 0; x < width; x++) {
  79111. var srcPos = (x + y * width) * 4;
  79112. byteArray[index] = srcData[srcPos + rOffset];
  79113. byteArray[index + 1] = srcData[srcPos + gOffset];
  79114. byteArray[index + 2] = srcData[srcPos + bOffset];
  79115. byteArray[index + 3] = srcData[srcPos + aOffset];
  79116. index += 4;
  79117. }
  79118. }
  79119. return byteArray;
  79120. };
  79121. DDSTools._ExtractLongWordOrder = function (value) {
  79122. if (value === 0 || value === 255 || value === -16777216) {
  79123. return 0;
  79124. }
  79125. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  79126. };
  79127. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  79128. var byteArray = new Uint8Array(dataLength);
  79129. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79130. var index = 0;
  79131. for (var y = 0; y < height; y++) {
  79132. for (var x = 0; x < width; x++) {
  79133. var srcPos = (x + y * width) * 3;
  79134. byteArray[index] = srcData[srcPos + rOffset];
  79135. byteArray[index + 1] = srcData[srcPos + gOffset];
  79136. byteArray[index + 2] = srcData[srcPos + bOffset];
  79137. index += 3;
  79138. }
  79139. }
  79140. return byteArray;
  79141. };
  79142. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  79143. var byteArray = new Uint8Array(dataLength);
  79144. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79145. var index = 0;
  79146. for (var y = 0; y < height; y++) {
  79147. for (var x = 0; x < width; x++) {
  79148. var srcPos = (x + y * width);
  79149. byteArray[index] = srcData[srcPos];
  79150. index++;
  79151. }
  79152. }
  79153. return byteArray;
  79154. };
  79155. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  79156. if (lodIndex === void 0) { lodIndex = -1; }
  79157. var ext = engine.getCaps().s3tc;
  79158. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  79159. var fourCC, width, height, dataLength = 0, dataOffset;
  79160. var byteArray, mipmapCount, mip;
  79161. var internalFormat = 0;
  79162. var format = 0;
  79163. var blockBytes = 1;
  79164. if (header[off_magic] !== DDS_MAGIC) {
  79165. BABYLON.Tools.Error("Invalid magic number in DDS header");
  79166. return;
  79167. }
  79168. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  79169. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  79170. return;
  79171. }
  79172. if (info.isCompressed && !ext) {
  79173. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  79174. return;
  79175. }
  79176. var bpp = header[off_RGBbpp];
  79177. dataOffset = header[off_size] + 4;
  79178. var computeFormats = false;
  79179. if (info.isFourCC) {
  79180. fourCC = header[off_pfFourCC];
  79181. switch (fourCC) {
  79182. case FOURCC_DXT1:
  79183. blockBytes = 8;
  79184. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  79185. break;
  79186. case FOURCC_DXT3:
  79187. blockBytes = 16;
  79188. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  79189. break;
  79190. case FOURCC_DXT5:
  79191. blockBytes = 16;
  79192. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  79193. break;
  79194. case FOURCC_D3DFMT_R16G16B16A16F:
  79195. computeFormats = true;
  79196. break;
  79197. case FOURCC_D3DFMT_R32G32B32A32F:
  79198. computeFormats = true;
  79199. break;
  79200. case FOURCC_DX10:
  79201. // There is an additionnal header so dataOffset need to be changed
  79202. dataOffset += 5 * 4; // 5 uints
  79203. var supported = false;
  79204. switch (info.dxgiFormat) {
  79205. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  79206. computeFormats = true;
  79207. supported = true;
  79208. break;
  79209. case DXGI_FORMAT_B8G8R8X8_UNORM:
  79210. info.isRGB = true;
  79211. info.isFourCC = false;
  79212. bpp = 32;
  79213. supported = true;
  79214. break;
  79215. }
  79216. if (supported) {
  79217. break;
  79218. }
  79219. default:
  79220. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  79221. return;
  79222. }
  79223. }
  79224. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  79225. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  79226. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  79227. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  79228. if (computeFormats) {
  79229. format = engine._getWebGLTextureType(info.textureType);
  79230. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79231. }
  79232. mipmapCount = 1;
  79233. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  79234. mipmapCount = Math.max(1, header[off_mipmapCount]);
  79235. }
  79236. for (var face = 0; face < faces; face++) {
  79237. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  79238. width = header[off_width];
  79239. height = header[off_height];
  79240. for (mip = 0; mip < mipmapCount; ++mip) {
  79241. if (lodIndex === -1 || lodIndex === mip) {
  79242. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  79243. var i = (lodIndex === -1) ? mip : 0;
  79244. if (!info.isCompressed && info.isFourCC) {
  79245. dataLength = width * height * 4;
  79246. var floatArray = null;
  79247. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  79248. if (bpp === 128) {
  79249. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79250. }
  79251. else if (bpp === 64) {
  79252. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79253. }
  79254. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79255. format = engine._getWebGLTextureType(info.textureType);
  79256. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79257. }
  79258. else {
  79259. if (bpp === 128) {
  79260. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79261. }
  79262. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  79263. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79264. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79265. format = engine._getWebGLTextureType(info.textureType);
  79266. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79267. }
  79268. else {
  79269. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79270. }
  79271. }
  79272. if (floatArray) {
  79273. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  79274. }
  79275. }
  79276. else if (info.isRGB) {
  79277. if (bpp === 24) {
  79278. dataLength = width * height * 3;
  79279. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  79280. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  79281. }
  79282. else {
  79283. dataLength = width * height * 4;
  79284. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  79285. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  79286. }
  79287. }
  79288. else if (info.isLuminance) {
  79289. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  79290. var unpaddedRowSize = width;
  79291. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  79292. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  79293. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  79294. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  79295. }
  79296. else {
  79297. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  79298. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  79299. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  79300. }
  79301. }
  79302. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  79303. width *= 0.5;
  79304. height *= 0.5;
  79305. width = Math.max(1.0, width);
  79306. height = Math.max(1.0, height);
  79307. }
  79308. if (currentFace !== undefined) {
  79309. // Loading a single face
  79310. break;
  79311. }
  79312. }
  79313. };
  79314. DDSTools.StoreLODInAlphaChannel = false;
  79315. return DDSTools;
  79316. }());
  79317. BABYLON.DDSTools = DDSTools;
  79318. })(BABYLON || (BABYLON = {}));
  79319. //# sourceMappingURL=babylon.dds.js.map
  79320. "use strict";
  79321. var BABYLON;
  79322. (function (BABYLON) {
  79323. /**
  79324. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  79325. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  79326. */
  79327. var KhronosTextureContainer = /** @class */ (function () {
  79328. /**
  79329. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  79330. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  79331. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  79332. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  79333. */
  79334. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  79335. this.arrayBuffer = arrayBuffer;
  79336. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  79337. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  79338. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  79339. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  79340. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  79341. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  79342. BABYLON.Tools.Error("texture missing KTX identifier");
  79343. return;
  79344. }
  79345. // load the reset of the header in native 32 bit int
  79346. var header = new Int32Array(this.arrayBuffer, 12, 13);
  79347. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  79348. var oppositeEndianess = header[0] === 0x01020304;
  79349. // read all the header elements in order they exist in the file, without modification (sans endainness)
  79350. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  79351. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  79352. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  79353. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  79354. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  79355. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  79356. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  79357. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  79358. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  79359. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  79360. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  79361. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  79362. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  79363. if (this.glType !== 0) {
  79364. BABYLON.Tools.Error("only compressed formats currently supported");
  79365. return;
  79366. }
  79367. else {
  79368. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  79369. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  79370. }
  79371. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  79372. BABYLON.Tools.Error("only 2D textures currently supported");
  79373. return;
  79374. }
  79375. if (this.numberOfArrayElements !== 0) {
  79376. BABYLON.Tools.Error("texture arrays not currently supported");
  79377. return;
  79378. }
  79379. if (this.numberOfFaces !== facesExpected) {
  79380. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  79381. return;
  79382. }
  79383. // we now have a completely validated file, so could use existence of loadType as success
  79384. // would need to make this more elaborate & adjust checks above to support more than one load type
  79385. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  79386. }
  79387. // not as fast hardware based, but will probably never need to use
  79388. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  79389. return ((val & 0xFF) << 24)
  79390. | ((val & 0xFF00) << 8)
  79391. | ((val >> 8) & 0xFF00)
  79392. | ((val >> 24) & 0xFF);
  79393. };
  79394. /**
  79395. * It is assumed that the texture has already been created & is currently bound
  79396. */
  79397. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  79398. switch (this.loadType) {
  79399. case KhronosTextureContainer.COMPRESSED_2D:
  79400. this._upload2DCompressedLevels(gl, loadMipmaps);
  79401. break;
  79402. case KhronosTextureContainer.TEX_2D:
  79403. case KhronosTextureContainer.COMPRESSED_3D:
  79404. case KhronosTextureContainer.TEX_3D:
  79405. }
  79406. };
  79407. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  79408. // initialize width & height for level 1
  79409. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  79410. var width = this.pixelWidth;
  79411. var height = this.pixelHeight;
  79412. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  79413. for (var level = 0; level < mipmapCount; level++) {
  79414. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  79415. for (var face = 0; face < this.numberOfFaces; face++) {
  79416. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  79417. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  79418. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  79419. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  79420. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  79421. }
  79422. width = Math.max(1.0, width * 0.5);
  79423. height = Math.max(1.0, height * 0.5);
  79424. }
  79425. };
  79426. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  79427. // load types
  79428. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  79429. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  79430. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  79431. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  79432. return KhronosTextureContainer;
  79433. }());
  79434. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  79435. })(BABYLON || (BABYLON = {}));
  79436. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  79437. "use strict";
  79438. var BABYLON;
  79439. (function (BABYLON) {
  79440. var Debug = /** @class */ (function () {
  79441. function Debug() {
  79442. }
  79443. Debug.AxesViewer = /** @class */ (function () {
  79444. function AxesViewer(scene, scaleLines) {
  79445. if (scaleLines === void 0) { scaleLines = 1; }
  79446. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79447. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79448. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79449. this.scaleLines = 1;
  79450. this.scaleLines = scaleLines;
  79451. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  79452. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  79453. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  79454. this._xmesh.renderingGroupId = 2;
  79455. this._ymesh.renderingGroupId = 2;
  79456. this._zmesh.renderingGroupId = 2;
  79457. this._xmesh.material.checkReadyOnlyOnce = true;
  79458. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  79459. this._ymesh.material.checkReadyOnlyOnce = true;
  79460. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  79461. this._zmesh.material.checkReadyOnlyOnce = true;
  79462. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  79463. this.scene = scene;
  79464. }
  79465. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  79466. var scaleLines = this.scaleLines;
  79467. if (this._xmesh) {
  79468. this._xmesh.position.copyFrom(position);
  79469. }
  79470. if (this._ymesh) {
  79471. this._ymesh.position.copyFrom(position);
  79472. }
  79473. if (this._zmesh) {
  79474. this._zmesh.position.copyFrom(position);
  79475. }
  79476. var point2 = this._xline[1];
  79477. point2.x = xaxis.x * scaleLines;
  79478. point2.y = xaxis.y * scaleLines;
  79479. point2.z = xaxis.z * scaleLines;
  79480. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  79481. point2 = this._yline[1];
  79482. point2.x = yaxis.x * scaleLines;
  79483. point2.y = yaxis.y * scaleLines;
  79484. point2.z = yaxis.z * scaleLines;
  79485. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  79486. point2 = this._zline[1];
  79487. point2.x = zaxis.x * scaleLines;
  79488. point2.y = zaxis.y * scaleLines;
  79489. point2.z = zaxis.z * scaleLines;
  79490. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  79491. };
  79492. AxesViewer.prototype.dispose = function () {
  79493. if (this._xmesh) {
  79494. this._xmesh.dispose();
  79495. }
  79496. if (this._ymesh) {
  79497. this._ymesh.dispose();
  79498. }
  79499. if (this._zmesh) {
  79500. this._zmesh.dispose();
  79501. }
  79502. this._xmesh = null;
  79503. this._ymesh = null;
  79504. this._zmesh = null;
  79505. this.scene = null;
  79506. };
  79507. return AxesViewer;
  79508. }());
  79509. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  79510. __extends(BoneAxesViewer, _super);
  79511. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  79512. if (scaleLines === void 0) { scaleLines = 1; }
  79513. var _this = _super.call(this, scene, scaleLines) || this;
  79514. _this.pos = BABYLON.Vector3.Zero();
  79515. _this.xaxis = BABYLON.Vector3.Zero();
  79516. _this.yaxis = BABYLON.Vector3.Zero();
  79517. _this.zaxis = BABYLON.Vector3.Zero();
  79518. _this.mesh = mesh;
  79519. _this.bone = bone;
  79520. return _this;
  79521. }
  79522. BoneAxesViewer.prototype.update = function () {
  79523. if (!this.mesh || !this.bone) {
  79524. return;
  79525. }
  79526. var bone = this.bone;
  79527. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  79528. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  79529. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  79530. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  79531. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  79532. };
  79533. BoneAxesViewer.prototype.dispose = function () {
  79534. if (this.mesh) {
  79535. this.mesh = null;
  79536. this.bone = null;
  79537. _super.prototype.dispose.call(this);
  79538. }
  79539. };
  79540. return BoneAxesViewer;
  79541. }(Debug.AxesViewer));
  79542. Debug.PhysicsViewer = /** @class */ (function () {
  79543. function PhysicsViewer(scene) {
  79544. this._impostors = [];
  79545. this._meshes = [];
  79546. this._numMeshes = 0;
  79547. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79548. var physicEngine = this._scene.getPhysicsEngine();
  79549. if (physicEngine) {
  79550. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  79551. }
  79552. }
  79553. PhysicsViewer.prototype._updateDebugMeshes = function () {
  79554. var plugin = this._physicsEnginePlugin;
  79555. for (var i = 0; i < this._numMeshes; i++) {
  79556. var impostor = this._impostors[i];
  79557. if (!impostor) {
  79558. continue;
  79559. }
  79560. if (impostor.isDisposed) {
  79561. this.hideImpostor(this._impostors[i--]);
  79562. }
  79563. else {
  79564. var mesh = this._meshes[i];
  79565. if (mesh && plugin) {
  79566. plugin.syncMeshWithImpostor(mesh, impostor);
  79567. }
  79568. }
  79569. }
  79570. };
  79571. PhysicsViewer.prototype.showImpostor = function (impostor) {
  79572. if (!this._scene) {
  79573. return;
  79574. }
  79575. for (var i = 0; i < this._numMeshes; i++) {
  79576. if (this._impostors[i] == impostor) {
  79577. return;
  79578. }
  79579. }
  79580. var debugMesh = this._getDebugMesh(impostor, this._scene);
  79581. if (debugMesh) {
  79582. this._impostors[this._numMeshes] = impostor;
  79583. this._meshes[this._numMeshes] = debugMesh;
  79584. if (this._numMeshes === 0) {
  79585. this._renderFunction = this._updateDebugMeshes.bind(this);
  79586. this._scene.registerBeforeRender(this._renderFunction);
  79587. }
  79588. this._numMeshes++;
  79589. }
  79590. };
  79591. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  79592. if (!impostor || !this._scene) {
  79593. return;
  79594. }
  79595. var removed = false;
  79596. for (var i = 0; i < this._numMeshes; i++) {
  79597. if (this._impostors[i] == impostor) {
  79598. var mesh = this._meshes[i];
  79599. if (!mesh) {
  79600. continue;
  79601. }
  79602. this._scene.removeMesh(mesh);
  79603. mesh.dispose();
  79604. this._numMeshes--;
  79605. if (this._numMeshes > 0) {
  79606. this._meshes[i] = this._meshes[this._numMeshes];
  79607. this._impostors[i] = this._impostors[this._numMeshes];
  79608. this._meshes[this._numMeshes] = null;
  79609. this._impostors[this._numMeshes] = null;
  79610. }
  79611. else {
  79612. this._meshes[0] = null;
  79613. this._impostors[0] = null;
  79614. }
  79615. removed = true;
  79616. break;
  79617. }
  79618. }
  79619. if (removed && this._numMeshes === 0) {
  79620. this._scene.unregisterBeforeRender(this._renderFunction);
  79621. }
  79622. };
  79623. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  79624. if (!this._debugMaterial) {
  79625. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  79626. this._debugMaterial.wireframe = true;
  79627. }
  79628. return this._debugMaterial;
  79629. };
  79630. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  79631. if (!this._debugBoxMesh) {
  79632. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  79633. this._debugBoxMesh.renderingGroupId = 1;
  79634. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  79635. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  79636. scene.removeMesh(this._debugBoxMesh);
  79637. }
  79638. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  79639. };
  79640. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  79641. if (!this._debugSphereMesh) {
  79642. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  79643. this._debugSphereMesh.renderingGroupId = 1;
  79644. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  79645. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  79646. scene.removeMesh(this._debugSphereMesh);
  79647. }
  79648. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  79649. };
  79650. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  79651. var mesh = null;
  79652. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  79653. mesh = this._getDebugBoxMesh(scene);
  79654. impostor.getBoxSizeToRef(mesh.scaling);
  79655. }
  79656. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  79657. mesh = this._getDebugSphereMesh(scene);
  79658. var radius = impostor.getRadius();
  79659. mesh.scaling.x = radius * 2;
  79660. mesh.scaling.y = radius * 2;
  79661. mesh.scaling.z = radius * 2;
  79662. }
  79663. return mesh;
  79664. };
  79665. PhysicsViewer.prototype.dispose = function () {
  79666. for (var i = 0; i < this._numMeshes; i++) {
  79667. this.hideImpostor(this._impostors[i]);
  79668. }
  79669. if (this._debugBoxMesh) {
  79670. this._debugBoxMesh.dispose();
  79671. }
  79672. if (this._debugSphereMesh) {
  79673. this._debugSphereMesh.dispose();
  79674. }
  79675. if (this._debugMaterial) {
  79676. this._debugMaterial.dispose();
  79677. }
  79678. this._impostors.length = 0;
  79679. this._scene = null;
  79680. this._physicsEnginePlugin = null;
  79681. };
  79682. return PhysicsViewer;
  79683. }());
  79684. Debug.SkeletonViewer = /** @class */ (function () {
  79685. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  79686. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  79687. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  79688. this.skeleton = skeleton;
  79689. this.mesh = mesh;
  79690. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  79691. this.renderingGroupId = renderingGroupId;
  79692. this.color = BABYLON.Color3.White();
  79693. this._debugLines = new Array();
  79694. this._isEnabled = false;
  79695. this._scene = scene;
  79696. this.update();
  79697. this._renderFunction = this.update.bind(this);
  79698. }
  79699. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  79700. get: function () {
  79701. return this._isEnabled;
  79702. },
  79703. set: function (value) {
  79704. if (this._isEnabled === value) {
  79705. return;
  79706. }
  79707. this._isEnabled = value;
  79708. if (value) {
  79709. this._scene.registerBeforeRender(this._renderFunction);
  79710. }
  79711. else {
  79712. this._scene.unregisterBeforeRender(this._renderFunction);
  79713. }
  79714. },
  79715. enumerable: true,
  79716. configurable: true
  79717. });
  79718. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  79719. if (x === void 0) { x = 0; }
  79720. if (y === void 0) { y = 0; }
  79721. if (z === void 0) { z = 0; }
  79722. var tmat = BABYLON.Tmp.Matrix[0];
  79723. var parentBone = bone.getParent();
  79724. tmat.copyFrom(bone.getLocalMatrix());
  79725. if (x !== 0 || y !== 0 || z !== 0) {
  79726. var tmat2 = BABYLON.Tmp.Matrix[1];
  79727. BABYLON.Matrix.IdentityToRef(tmat2);
  79728. tmat2.m[12] = x;
  79729. tmat2.m[13] = y;
  79730. tmat2.m[14] = z;
  79731. tmat2.multiplyToRef(tmat, tmat);
  79732. }
  79733. if (parentBone) {
  79734. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  79735. }
  79736. tmat.multiplyToRef(meshMat, tmat);
  79737. position.x = tmat.m[12];
  79738. position.y = tmat.m[13];
  79739. position.z = tmat.m[14];
  79740. };
  79741. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  79742. var len = bones.length;
  79743. var meshPos = this.mesh.position;
  79744. for (var i = 0; i < len; i++) {
  79745. var bone = bones[i];
  79746. var points = this._debugLines[i];
  79747. if (!points) {
  79748. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79749. this._debugLines[i] = points;
  79750. }
  79751. this._getBonePosition(points[0], bone, meshMat);
  79752. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  79753. points[0].subtractInPlace(meshPos);
  79754. points[1].subtractInPlace(meshPos);
  79755. }
  79756. };
  79757. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  79758. var len = bones.length;
  79759. var boneNum = 0;
  79760. var meshPos = this.mesh.position;
  79761. for (var i = len - 1; i >= 0; i--) {
  79762. var childBone = bones[i];
  79763. var parentBone = childBone.getParent();
  79764. if (!parentBone) {
  79765. continue;
  79766. }
  79767. var points = this._debugLines[boneNum];
  79768. if (!points) {
  79769. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79770. this._debugLines[boneNum] = points;
  79771. }
  79772. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  79773. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  79774. points[0].subtractInPlace(meshPos);
  79775. points[1].subtractInPlace(meshPos);
  79776. boneNum++;
  79777. }
  79778. };
  79779. SkeletonViewer.prototype.update = function () {
  79780. if (this.autoUpdateBonesMatrices) {
  79781. this.skeleton.computeAbsoluteTransforms();
  79782. }
  79783. if (this.skeleton.bones[0].length === undefined) {
  79784. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  79785. }
  79786. else {
  79787. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  79788. }
  79789. if (!this._debugMesh) {
  79790. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  79791. this._debugMesh.renderingGroupId = this.renderingGroupId;
  79792. }
  79793. else {
  79794. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  79795. }
  79796. this._debugMesh.position.copyFrom(this.mesh.position);
  79797. this._debugMesh.color = this.color;
  79798. };
  79799. SkeletonViewer.prototype.dispose = function () {
  79800. if (this._debugMesh) {
  79801. this.isEnabled = false;
  79802. this._debugMesh.dispose();
  79803. this._debugMesh = null;
  79804. }
  79805. };
  79806. return SkeletonViewer;
  79807. }());
  79808. return Debug;
  79809. }());
  79810. BABYLON.Debug = Debug;
  79811. })(BABYLON || (BABYLON = {}));
  79812. //# sourceMappingURL=babylon.debugModules.js.map
  79813. "use strict";
  79814. var BABYLON;
  79815. (function (BABYLON) {
  79816. var RayHelper = /** @class */ (function () {
  79817. function RayHelper(ray) {
  79818. this.ray = ray;
  79819. }
  79820. RayHelper.CreateAndShow = function (ray, scene, color) {
  79821. var helper = new RayHelper(ray);
  79822. helper.show(scene, color);
  79823. return helper;
  79824. };
  79825. RayHelper.prototype.show = function (scene, color) {
  79826. if (!this._renderFunction && this.ray) {
  79827. var ray = this.ray;
  79828. this._renderFunction = this._render.bind(this);
  79829. this._scene = scene;
  79830. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  79831. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  79832. if (this._renderFunction) {
  79833. this._scene.registerBeforeRender(this._renderFunction);
  79834. }
  79835. }
  79836. if (color && this._renderLine) {
  79837. this._renderLine.color.copyFrom(color);
  79838. }
  79839. };
  79840. RayHelper.prototype.hide = function () {
  79841. if (this._renderFunction && this._scene) {
  79842. this._scene.unregisterBeforeRender(this._renderFunction);
  79843. this._scene = null;
  79844. this._renderFunction = null;
  79845. if (this._renderLine) {
  79846. this._renderLine.dispose();
  79847. this._renderLine = null;
  79848. }
  79849. this._renderPoints = [];
  79850. }
  79851. };
  79852. RayHelper.prototype._render = function () {
  79853. var ray = this.ray;
  79854. if (!ray) {
  79855. return;
  79856. }
  79857. var point = this._renderPoints[1];
  79858. var len = Math.min(ray.length, 1000000);
  79859. point.copyFrom(ray.direction);
  79860. point.scaleInPlace(len);
  79861. point.addInPlace(ray.origin);
  79862. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  79863. };
  79864. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  79865. this._attachedToMesh = mesh;
  79866. var ray = this.ray;
  79867. if (!ray) {
  79868. return;
  79869. }
  79870. if (!ray.direction) {
  79871. ray.direction = BABYLON.Vector3.Zero();
  79872. }
  79873. if (!ray.origin) {
  79874. ray.origin = BABYLON.Vector3.Zero();
  79875. }
  79876. if (length) {
  79877. ray.length = length;
  79878. }
  79879. if (!meshSpaceOrigin) {
  79880. meshSpaceOrigin = BABYLON.Vector3.Zero();
  79881. }
  79882. if (!meshSpaceDirection) {
  79883. // -1 so that this will work with Mesh.lookAt
  79884. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  79885. }
  79886. if (!this._meshSpaceDirection) {
  79887. this._meshSpaceDirection = meshSpaceDirection.clone();
  79888. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  79889. }
  79890. else {
  79891. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  79892. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  79893. }
  79894. if (!this._updateToMeshFunction) {
  79895. this._updateToMeshFunction = this._updateToMesh.bind(this);
  79896. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  79897. }
  79898. this._updateToMesh();
  79899. };
  79900. RayHelper.prototype.detachFromMesh = function () {
  79901. if (this._attachedToMesh) {
  79902. if (this._updateToMeshFunction) {
  79903. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  79904. }
  79905. this._attachedToMesh = null;
  79906. this._updateToMeshFunction = null;
  79907. }
  79908. };
  79909. RayHelper.prototype._updateToMesh = function () {
  79910. var ray = this.ray;
  79911. if (!this._attachedToMesh || !ray) {
  79912. return;
  79913. }
  79914. if (this._attachedToMesh._isDisposed) {
  79915. this.detachFromMesh();
  79916. return;
  79917. }
  79918. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  79919. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  79920. };
  79921. RayHelper.prototype.dispose = function () {
  79922. this.hide();
  79923. this.detachFromMesh();
  79924. this.ray = null;
  79925. };
  79926. return RayHelper;
  79927. }());
  79928. BABYLON.RayHelper = RayHelper;
  79929. })(BABYLON || (BABYLON = {}));
  79930. //# sourceMappingURL=babylon.rayHelper.js.map
  79931. "use strict";
  79932. var BABYLON;
  79933. (function (BABYLON) {
  79934. // load the inspector using require, if not present in the global namespace.
  79935. var DebugLayer = /** @class */ (function () {
  79936. function DebugLayer(scene) {
  79937. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  79938. this._scene = scene;
  79939. // load inspector using require, if it doesn't exist on the global namespace.
  79940. }
  79941. /** Creates the inspector window. */
  79942. DebugLayer.prototype._createInspector = function (config) {
  79943. if (config === void 0) { config = {}; }
  79944. var popup = config.popup || false;
  79945. var initialTab = config.initialTab || 0;
  79946. var parentElement = config.parentElement || null;
  79947. if (!this._inspector) {
  79948. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  79949. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  79950. } // else nothing to do,; instance is already existing
  79951. };
  79952. DebugLayer.prototype.isVisible = function () {
  79953. if (!this._inspector) {
  79954. return false;
  79955. }
  79956. return true;
  79957. };
  79958. DebugLayer.prototype.hide = function () {
  79959. if (this._inspector) {
  79960. try {
  79961. this._inspector.dispose();
  79962. }
  79963. catch (e) {
  79964. // If the inspector has been removed directly from the inspector tool
  79965. }
  79966. this._inspector = null;
  79967. }
  79968. };
  79969. DebugLayer.prototype.show = function (config) {
  79970. if (config === void 0) { config = {}; }
  79971. if (typeof this.BJSINSPECTOR == 'undefined') {
  79972. // Load inspector and add it to the DOM
  79973. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  79974. }
  79975. else {
  79976. // Otherwise creates the inspector
  79977. this._createInspector(config);
  79978. }
  79979. };
  79980. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  79981. return DebugLayer;
  79982. }());
  79983. BABYLON.DebugLayer = DebugLayer;
  79984. })(BABYLON || (BABYLON = {}));
  79985. //# sourceMappingURL=babylon.debugLayer.js.map
  79986. "use strict";
  79987. var BABYLON;
  79988. (function (BABYLON) {
  79989. var BoundingBoxRenderer = /** @class */ (function () {
  79990. function BoundingBoxRenderer(scene) {
  79991. this.frontColor = new BABYLON.Color3(1, 1, 1);
  79992. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  79993. this.showBackLines = true;
  79994. this.renderList = new BABYLON.SmartArray(32);
  79995. this._vertexBuffers = {};
  79996. this._scene = scene;
  79997. }
  79998. BoundingBoxRenderer.prototype._prepareRessources = function () {
  79999. if (this._colorShader) {
  80000. return;
  80001. }
  80002. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  80003. attributes: [BABYLON.VertexBuffer.PositionKind],
  80004. uniforms: ["world", "viewProjection", "color"]
  80005. });
  80006. var engine = this._scene.getEngine();
  80007. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  80008. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  80009. this._createIndexBuffer();
  80010. };
  80011. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  80012. var engine = this._scene.getEngine();
  80013. 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]);
  80014. };
  80015. BoundingBoxRenderer.prototype._rebuild = function () {
  80016. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80017. if (vb) {
  80018. vb._rebuild();
  80019. }
  80020. this._createIndexBuffer();
  80021. };
  80022. BoundingBoxRenderer.prototype.reset = function () {
  80023. this.renderList.reset();
  80024. };
  80025. BoundingBoxRenderer.prototype.render = function () {
  80026. if (this.renderList.length === 0) {
  80027. return;
  80028. }
  80029. this._prepareRessources();
  80030. if (!this._colorShader.isReady()) {
  80031. return;
  80032. }
  80033. var engine = this._scene.getEngine();
  80034. engine.setDepthWrite(false);
  80035. this._colorShader._preBind();
  80036. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  80037. var boundingBox = this.renderList.data[boundingBoxIndex];
  80038. var min = boundingBox.minimum;
  80039. var max = boundingBox.maximum;
  80040. var diff = max.subtract(min);
  80041. var median = min.add(diff.scale(0.5));
  80042. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  80043. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  80044. .multiply(boundingBox.getWorldMatrix());
  80045. // VBOs
  80046. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  80047. if (this.showBackLines) {
  80048. // Back
  80049. engine.setDepthFunctionToGreaterOrEqual();
  80050. this._scene.resetCachedMaterial();
  80051. this._colorShader.setColor4("color", this.backColor.toColor4());
  80052. this._colorShader.bind(worldMatrix);
  80053. // Draw order
  80054. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80055. }
  80056. // Front
  80057. engine.setDepthFunctionToLess();
  80058. this._scene.resetCachedMaterial();
  80059. this._colorShader.setColor4("color", this.frontColor.toColor4());
  80060. this._colorShader.bind(worldMatrix);
  80061. // Draw order
  80062. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80063. }
  80064. this._colorShader.unbind();
  80065. engine.setDepthFunctionToLessOrEqual();
  80066. engine.setDepthWrite(true);
  80067. };
  80068. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  80069. this._prepareRessources();
  80070. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  80071. return;
  80072. }
  80073. var engine = this._scene.getEngine();
  80074. engine.setDepthWrite(false);
  80075. engine.setColorWrite(false);
  80076. this._colorShader._preBind();
  80077. var boundingBox = mesh._boundingInfo.boundingBox;
  80078. var min = boundingBox.minimum;
  80079. var max = boundingBox.maximum;
  80080. var diff = max.subtract(min);
  80081. var median = min.add(diff.scale(0.5));
  80082. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  80083. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  80084. .multiply(boundingBox.getWorldMatrix());
  80085. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  80086. engine.setDepthFunctionToLess();
  80087. this._scene.resetCachedMaterial();
  80088. this._colorShader.bind(worldMatrix);
  80089. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80090. this._colorShader.unbind();
  80091. engine.setDepthFunctionToLessOrEqual();
  80092. engine.setDepthWrite(true);
  80093. engine.setColorWrite(true);
  80094. };
  80095. BoundingBoxRenderer.prototype.dispose = function () {
  80096. if (!this._colorShader) {
  80097. return;
  80098. }
  80099. this.renderList.dispose();
  80100. this._colorShader.dispose();
  80101. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80102. if (buffer) {
  80103. buffer.dispose();
  80104. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  80105. }
  80106. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  80107. };
  80108. return BoundingBoxRenderer;
  80109. }());
  80110. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  80111. })(BABYLON || (BABYLON = {}));
  80112. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  80113. "use strict";
  80114. var BABYLON;
  80115. (function (BABYLON) {
  80116. var MorphTarget = /** @class */ (function () {
  80117. function MorphTarget(name, influence) {
  80118. if (influence === void 0) { influence = 0; }
  80119. this.name = name;
  80120. this.animations = new Array();
  80121. this._positions = null;
  80122. this._normals = null;
  80123. this._tangents = null;
  80124. this.onInfluenceChanged = new BABYLON.Observable();
  80125. this.influence = influence;
  80126. }
  80127. Object.defineProperty(MorphTarget.prototype, "influence", {
  80128. get: function () {
  80129. return this._influence;
  80130. },
  80131. set: function (influence) {
  80132. if (this._influence === influence) {
  80133. return;
  80134. }
  80135. var previous = this._influence;
  80136. this._influence = influence;
  80137. if (this.onInfluenceChanged.hasObservers) {
  80138. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  80139. }
  80140. },
  80141. enumerable: true,
  80142. configurable: true
  80143. });
  80144. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  80145. get: function () {
  80146. return !!this._positions;
  80147. },
  80148. enumerable: true,
  80149. configurable: true
  80150. });
  80151. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  80152. get: function () {
  80153. return !!this._normals;
  80154. },
  80155. enumerable: true,
  80156. configurable: true
  80157. });
  80158. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  80159. get: function () {
  80160. return !!this._tangents;
  80161. },
  80162. enumerable: true,
  80163. configurable: true
  80164. });
  80165. MorphTarget.prototype.setPositions = function (data) {
  80166. this._positions = data;
  80167. };
  80168. MorphTarget.prototype.getPositions = function () {
  80169. return this._positions;
  80170. };
  80171. MorphTarget.prototype.setNormals = function (data) {
  80172. this._normals = data;
  80173. };
  80174. MorphTarget.prototype.getNormals = function () {
  80175. return this._normals;
  80176. };
  80177. MorphTarget.prototype.setTangents = function (data) {
  80178. this._tangents = data;
  80179. };
  80180. MorphTarget.prototype.getTangents = function () {
  80181. return this._tangents;
  80182. };
  80183. /**
  80184. * Serializes the current target into a Serialization object.
  80185. * Returns the serialized object.
  80186. */
  80187. MorphTarget.prototype.serialize = function () {
  80188. var serializationObject = {};
  80189. serializationObject.name = this.name;
  80190. serializationObject.influence = this.influence;
  80191. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  80192. if (this.hasNormals) {
  80193. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  80194. }
  80195. if (this.hasTangents) {
  80196. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  80197. }
  80198. // Animations
  80199. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  80200. return serializationObject;
  80201. };
  80202. // Statics
  80203. MorphTarget.Parse = function (serializationObject) {
  80204. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  80205. result.setPositions(serializationObject.positions);
  80206. if (serializationObject.normals) {
  80207. result.setNormals(serializationObject.normals);
  80208. }
  80209. if (serializationObject.tangents) {
  80210. result.setTangents(serializationObject.tangents);
  80211. }
  80212. // Animations
  80213. if (serializationObject.animations) {
  80214. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  80215. var parsedAnimation = serializationObject.animations[animationIndex];
  80216. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  80217. }
  80218. }
  80219. return result;
  80220. };
  80221. MorphTarget.FromMesh = function (mesh, name, influence) {
  80222. if (!name) {
  80223. name = mesh.name;
  80224. }
  80225. var result = new MorphTarget(name, influence);
  80226. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  80227. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  80228. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  80229. }
  80230. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  80231. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  80232. }
  80233. return result;
  80234. };
  80235. return MorphTarget;
  80236. }());
  80237. BABYLON.MorphTarget = MorphTarget;
  80238. })(BABYLON || (BABYLON = {}));
  80239. //# sourceMappingURL=babylon.morphTarget.js.map
  80240. "use strict";
  80241. var BABYLON;
  80242. (function (BABYLON) {
  80243. var MorphTargetManager = /** @class */ (function () {
  80244. function MorphTargetManager(scene) {
  80245. if (scene === void 0) { scene = null; }
  80246. this._targets = new Array();
  80247. this._targetObservable = new Array();
  80248. this._activeTargets = new BABYLON.SmartArray(16);
  80249. this._supportsNormals = false;
  80250. this._supportsTangents = false;
  80251. this._vertexCount = 0;
  80252. this._uniqueId = 0;
  80253. this._tempInfluences = new Array();
  80254. if (!scene) {
  80255. scene = BABYLON.Engine.LastCreatedScene;
  80256. }
  80257. this._scene = scene;
  80258. if (this._scene) {
  80259. this._scene.morphTargetManagers.push(this);
  80260. this._uniqueId = this._scene.getUniqueId();
  80261. }
  80262. }
  80263. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  80264. get: function () {
  80265. return this._uniqueId;
  80266. },
  80267. enumerable: true,
  80268. configurable: true
  80269. });
  80270. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  80271. get: function () {
  80272. return this._vertexCount;
  80273. },
  80274. enumerable: true,
  80275. configurable: true
  80276. });
  80277. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  80278. get: function () {
  80279. return this._supportsNormals;
  80280. },
  80281. enumerable: true,
  80282. configurable: true
  80283. });
  80284. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  80285. get: function () {
  80286. return this._supportsTangents;
  80287. },
  80288. enumerable: true,
  80289. configurable: true
  80290. });
  80291. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  80292. get: function () {
  80293. return this._targets.length;
  80294. },
  80295. enumerable: true,
  80296. configurable: true
  80297. });
  80298. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  80299. get: function () {
  80300. return this._activeTargets.length;
  80301. },
  80302. enumerable: true,
  80303. configurable: true
  80304. });
  80305. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  80306. get: function () {
  80307. return this._influences;
  80308. },
  80309. enumerable: true,
  80310. configurable: true
  80311. });
  80312. MorphTargetManager.prototype.getActiveTarget = function (index) {
  80313. return this._activeTargets.data[index];
  80314. };
  80315. MorphTargetManager.prototype.getTarget = function (index) {
  80316. return this._targets[index];
  80317. };
  80318. MorphTargetManager.prototype.addTarget = function (target) {
  80319. var _this = this;
  80320. this._targets.push(target);
  80321. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  80322. _this._syncActiveTargets(needUpdate);
  80323. }));
  80324. this._syncActiveTargets(true);
  80325. };
  80326. MorphTargetManager.prototype.removeTarget = function (target) {
  80327. var index = this._targets.indexOf(target);
  80328. if (index >= 0) {
  80329. this._targets.splice(index, 1);
  80330. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  80331. this._syncActiveTargets(true);
  80332. }
  80333. };
  80334. /**
  80335. * Serializes the current manager into a Serialization object.
  80336. * Returns the serialized object.
  80337. */
  80338. MorphTargetManager.prototype.serialize = function () {
  80339. var serializationObject = {};
  80340. serializationObject.id = this.uniqueId;
  80341. serializationObject.targets = [];
  80342. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  80343. var target = _a[_i];
  80344. serializationObject.targets.push(target.serialize());
  80345. }
  80346. return serializationObject;
  80347. };
  80348. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  80349. var influenceCount = 0;
  80350. this._activeTargets.reset();
  80351. this._supportsNormals = true;
  80352. this._supportsTangents = true;
  80353. this._vertexCount = 0;
  80354. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  80355. var target = _a[_i];
  80356. this._activeTargets.push(target);
  80357. this._tempInfluences[influenceCount++] = target.influence;
  80358. var positions = target.getPositions();
  80359. if (positions) {
  80360. this._supportsNormals = this._supportsNormals && target.hasNormals;
  80361. this._supportsTangents = this._supportsTangents && target.hasTangents;
  80362. var vertexCount = positions.length / 3;
  80363. if (this._vertexCount === 0) {
  80364. this._vertexCount = vertexCount;
  80365. }
  80366. else if (this._vertexCount !== vertexCount) {
  80367. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  80368. return;
  80369. }
  80370. }
  80371. }
  80372. if (!this._influences || this._influences.length !== influenceCount) {
  80373. this._influences = new Float32Array(influenceCount);
  80374. }
  80375. for (var index = 0; index < influenceCount; index++) {
  80376. this._influences[index] = this._tempInfluences[index];
  80377. }
  80378. if (needUpdate && this._scene) {
  80379. // Flag meshes as dirty to resync with the active targets
  80380. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  80381. var mesh = _c[_b];
  80382. if (mesh.morphTargetManager === this) {
  80383. mesh._syncGeometryWithMorphTargetManager();
  80384. }
  80385. }
  80386. }
  80387. };
  80388. // Statics
  80389. MorphTargetManager.Parse = function (serializationObject, scene) {
  80390. var result = new MorphTargetManager(scene);
  80391. result._uniqueId = serializationObject.id;
  80392. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  80393. var targetData = _a[_i];
  80394. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  80395. }
  80396. return result;
  80397. };
  80398. return MorphTargetManager;
  80399. }());
  80400. BABYLON.MorphTargetManager = MorphTargetManager;
  80401. })(BABYLON || (BABYLON = {}));
  80402. //# sourceMappingURL=babylon.morphTargetManager.js.map
  80403. "use strict";
  80404. var BABYLON;
  80405. (function (BABYLON) {
  80406. var Octree = /** @class */ (function () {
  80407. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  80408. if (maxDepth === void 0) { maxDepth = 2; }
  80409. this.maxDepth = maxDepth;
  80410. this.dynamicContent = new Array();
  80411. this._maxBlockCapacity = maxBlockCapacity || 64;
  80412. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  80413. this._creationFunc = creationFunc;
  80414. }
  80415. // Methods
  80416. Octree.prototype.update = function (worldMin, worldMax, entries) {
  80417. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  80418. };
  80419. Octree.prototype.addMesh = function (entry) {
  80420. for (var index = 0; index < this.blocks.length; index++) {
  80421. var block = this.blocks[index];
  80422. block.addEntry(entry);
  80423. }
  80424. };
  80425. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  80426. this._selectionContent.reset();
  80427. for (var index = 0; index < this.blocks.length; index++) {
  80428. var block = this.blocks[index];
  80429. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  80430. }
  80431. if (allowDuplicate) {
  80432. this._selectionContent.concat(this.dynamicContent);
  80433. }
  80434. else {
  80435. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  80436. }
  80437. return this._selectionContent;
  80438. };
  80439. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  80440. this._selectionContent.reset();
  80441. for (var index = 0; index < this.blocks.length; index++) {
  80442. var block = this.blocks[index];
  80443. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  80444. }
  80445. if (allowDuplicate) {
  80446. this._selectionContent.concat(this.dynamicContent);
  80447. }
  80448. else {
  80449. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  80450. }
  80451. return this._selectionContent;
  80452. };
  80453. Octree.prototype.intersectsRay = function (ray) {
  80454. this._selectionContent.reset();
  80455. for (var index = 0; index < this.blocks.length; index++) {
  80456. var block = this.blocks[index];
  80457. block.intersectsRay(ray, this._selectionContent);
  80458. }
  80459. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  80460. return this._selectionContent;
  80461. };
  80462. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  80463. target.blocks = new Array();
  80464. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  80465. // Segmenting space
  80466. for (var x = 0; x < 2; x++) {
  80467. for (var y = 0; y < 2; y++) {
  80468. for (var z = 0; z < 2; z++) {
  80469. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  80470. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  80471. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  80472. block.addEntries(entries);
  80473. target.blocks.push(block);
  80474. }
  80475. }
  80476. }
  80477. };
  80478. Octree.CreationFuncForMeshes = function (entry, block) {
  80479. var boundingInfo = entry.getBoundingInfo();
  80480. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  80481. block.entries.push(entry);
  80482. }
  80483. };
  80484. Octree.CreationFuncForSubMeshes = function (entry, block) {
  80485. var boundingInfo = entry.getBoundingInfo();
  80486. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  80487. block.entries.push(entry);
  80488. }
  80489. };
  80490. return Octree;
  80491. }());
  80492. BABYLON.Octree = Octree;
  80493. })(BABYLON || (BABYLON = {}));
  80494. //# sourceMappingURL=babylon.octree.js.map
  80495. "use strict";
  80496. var BABYLON;
  80497. (function (BABYLON) {
  80498. var OctreeBlock = /** @class */ (function () {
  80499. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  80500. this.entries = new Array();
  80501. this._boundingVectors = new Array();
  80502. this._capacity = capacity;
  80503. this._depth = depth;
  80504. this._maxDepth = maxDepth;
  80505. this._creationFunc = creationFunc;
  80506. this._minPoint = minPoint;
  80507. this._maxPoint = maxPoint;
  80508. this._boundingVectors.push(minPoint.clone());
  80509. this._boundingVectors.push(maxPoint.clone());
  80510. this._boundingVectors.push(minPoint.clone());
  80511. this._boundingVectors[2].x = maxPoint.x;
  80512. this._boundingVectors.push(minPoint.clone());
  80513. this._boundingVectors[3].y = maxPoint.y;
  80514. this._boundingVectors.push(minPoint.clone());
  80515. this._boundingVectors[4].z = maxPoint.z;
  80516. this._boundingVectors.push(maxPoint.clone());
  80517. this._boundingVectors[5].z = minPoint.z;
  80518. this._boundingVectors.push(maxPoint.clone());
  80519. this._boundingVectors[6].x = minPoint.x;
  80520. this._boundingVectors.push(maxPoint.clone());
  80521. this._boundingVectors[7].y = minPoint.y;
  80522. }
  80523. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  80524. // Property
  80525. get: function () {
  80526. return this._capacity;
  80527. },
  80528. enumerable: true,
  80529. configurable: true
  80530. });
  80531. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  80532. get: function () {
  80533. return this._minPoint;
  80534. },
  80535. enumerable: true,
  80536. configurable: true
  80537. });
  80538. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  80539. get: function () {
  80540. return this._maxPoint;
  80541. },
  80542. enumerable: true,
  80543. configurable: true
  80544. });
  80545. // Methods
  80546. OctreeBlock.prototype.addEntry = function (entry) {
  80547. if (this.blocks) {
  80548. for (var index = 0; index < this.blocks.length; index++) {
  80549. var block = this.blocks[index];
  80550. block.addEntry(entry);
  80551. }
  80552. return;
  80553. }
  80554. this._creationFunc(entry, this);
  80555. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  80556. this.createInnerBlocks();
  80557. }
  80558. };
  80559. OctreeBlock.prototype.addEntries = function (entries) {
  80560. for (var index = 0; index < entries.length; index++) {
  80561. var mesh = entries[index];
  80562. this.addEntry(mesh);
  80563. }
  80564. };
  80565. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  80566. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  80567. if (this.blocks) {
  80568. for (var index = 0; index < this.blocks.length; index++) {
  80569. var block = this.blocks[index];
  80570. block.select(frustumPlanes, selection, allowDuplicate);
  80571. }
  80572. return;
  80573. }
  80574. if (allowDuplicate) {
  80575. selection.concat(this.entries);
  80576. }
  80577. else {
  80578. selection.concatWithNoDuplicate(this.entries);
  80579. }
  80580. }
  80581. };
  80582. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  80583. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  80584. if (this.blocks) {
  80585. for (var index = 0; index < this.blocks.length; index++) {
  80586. var block = this.blocks[index];
  80587. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  80588. }
  80589. return;
  80590. }
  80591. if (allowDuplicate) {
  80592. selection.concat(this.entries);
  80593. }
  80594. else {
  80595. selection.concatWithNoDuplicate(this.entries);
  80596. }
  80597. }
  80598. };
  80599. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  80600. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  80601. if (this.blocks) {
  80602. for (var index = 0; index < this.blocks.length; index++) {
  80603. var block = this.blocks[index];
  80604. block.intersectsRay(ray, selection);
  80605. }
  80606. return;
  80607. }
  80608. selection.concatWithNoDuplicate(this.entries);
  80609. }
  80610. };
  80611. OctreeBlock.prototype.createInnerBlocks = function () {
  80612. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  80613. };
  80614. return OctreeBlock;
  80615. }());
  80616. BABYLON.OctreeBlock = OctreeBlock;
  80617. })(BABYLON || (BABYLON = {}));
  80618. //# sourceMappingURL=babylon.octreeBlock.js.map
  80619. "use strict";
  80620. var BABYLON;
  80621. (function (BABYLON) {
  80622. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  80623. __extends(VRDistortionCorrectionPostProcess, _super);
  80624. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  80625. var _this = _super.call(this, name, "vrDistortionCorrection", [
  80626. 'LensCenter',
  80627. 'Scale',
  80628. 'ScaleIn',
  80629. 'HmdWarpParam'
  80630. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  80631. _this._isRightEye = isRightEye;
  80632. _this._distortionFactors = vrMetrics.distortionK;
  80633. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  80634. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  80635. _this.adaptScaleToCurrentViewport = true;
  80636. _this.onSizeChangedObservable.add(function () {
  80637. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  80638. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  80639. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  80640. });
  80641. _this.onApplyObservable.add(function (effect) {
  80642. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  80643. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  80644. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  80645. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  80646. });
  80647. return _this;
  80648. }
  80649. return VRDistortionCorrectionPostProcess;
  80650. }(BABYLON.PostProcess));
  80651. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  80652. })(BABYLON || (BABYLON = {}));
  80653. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  80654. "use strict";
  80655. var BABYLON;
  80656. (function (BABYLON) {
  80657. var AnaglyphPostProcess = /** @class */ (function (_super) {
  80658. __extends(AnaglyphPostProcess, _super);
  80659. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  80660. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  80661. _this._passedProcess = rigCameras[0]._rigPostProcess;
  80662. _this.onApplyObservable.add(function (effect) {
  80663. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  80664. });
  80665. return _this;
  80666. }
  80667. return AnaglyphPostProcess;
  80668. }(BABYLON.PostProcess));
  80669. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  80670. })(BABYLON || (BABYLON = {}));
  80671. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  80672. "use strict";
  80673. var BABYLON;
  80674. (function (BABYLON) {
  80675. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  80676. __extends(StereoscopicInterlacePostProcess, _super);
  80677. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  80678. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  80679. _this._passedProcess = rigCameras[0]._rigPostProcess;
  80680. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  80681. _this.onSizeChangedObservable.add(function () {
  80682. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  80683. });
  80684. _this.onApplyObservable.add(function (effect) {
  80685. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  80686. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  80687. });
  80688. return _this;
  80689. }
  80690. return StereoscopicInterlacePostProcess;
  80691. }(BABYLON.PostProcess));
  80692. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  80693. })(BABYLON || (BABYLON = {}));
  80694. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  80695. "use strict";
  80696. var BABYLON;
  80697. (function (BABYLON) {
  80698. /**
  80699. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  80700. * Screen rotation is taken into account.
  80701. */
  80702. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  80703. function FreeCameraDeviceOrientationInput() {
  80704. var _this = this;
  80705. this._screenOrientationAngle = 0;
  80706. this._screenQuaternion = new BABYLON.Quaternion();
  80707. this._alpha = 0;
  80708. this._beta = 0;
  80709. this._gamma = 0;
  80710. this._orientationChanged = function () {
  80711. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  80712. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  80713. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  80714. };
  80715. this._deviceOrientation = function (evt) {
  80716. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  80717. _this._beta = evt.beta !== null ? evt.beta : 0;
  80718. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  80719. };
  80720. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  80721. this._orientationChanged();
  80722. }
  80723. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  80724. get: function () {
  80725. return this._camera;
  80726. },
  80727. set: function (camera) {
  80728. this._camera = camera;
  80729. if (this._camera != null && !this._camera.rotationQuaternion) {
  80730. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  80731. }
  80732. },
  80733. enumerable: true,
  80734. configurable: true
  80735. });
  80736. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  80737. window.addEventListener("orientationchange", this._orientationChanged);
  80738. window.addEventListener("deviceorientation", this._deviceOrientation);
  80739. //In certain cases, the attach control is called AFTER orientation was changed,
  80740. //So this is needed.
  80741. this._orientationChanged();
  80742. };
  80743. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  80744. window.removeEventListener("orientationchange", this._orientationChanged);
  80745. window.removeEventListener("deviceorientation", this._deviceOrientation);
  80746. };
  80747. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  80748. //if no device orientation provided, don't update the rotation.
  80749. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  80750. if (!this._alpha)
  80751. return;
  80752. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  80753. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  80754. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  80755. //Mirror on XY Plane
  80756. this._camera.rotationQuaternion.z *= -1;
  80757. this._camera.rotationQuaternion.w *= -1;
  80758. };
  80759. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  80760. return "FreeCameraDeviceOrientationInput";
  80761. };
  80762. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  80763. return "deviceOrientation";
  80764. };
  80765. return FreeCameraDeviceOrientationInput;
  80766. }());
  80767. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  80768. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  80769. })(BABYLON || (BABYLON = {}));
  80770. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  80771. "use strict";
  80772. var BABYLON;
  80773. (function (BABYLON) {
  80774. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  80775. function ArcRotateCameraVRDeviceOrientationInput() {
  80776. this.alphaCorrection = 1;
  80777. this.betaCorrection = 1;
  80778. this.gammaCorrection = 1;
  80779. this._alpha = 0;
  80780. this._gamma = 0;
  80781. this._dirty = false;
  80782. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  80783. }
  80784. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  80785. this.camera.attachControl(element, noPreventDefault);
  80786. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  80787. };
  80788. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  80789. if (evt.alpha !== null) {
  80790. this._alpha = +evt.alpha | 0;
  80791. }
  80792. if (evt.gamma !== null) {
  80793. this._gamma = +evt.gamma | 0;
  80794. }
  80795. this._dirty = true;
  80796. };
  80797. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  80798. if (this._dirty) {
  80799. this._dirty = false;
  80800. if (this._gamma < 0) {
  80801. this._gamma = 180 + this._gamma;
  80802. }
  80803. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  80804. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  80805. }
  80806. };
  80807. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  80808. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  80809. };
  80810. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  80811. return "ArcRotateCameraVRDeviceOrientationInput";
  80812. };
  80813. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  80814. return "VRDeviceOrientation";
  80815. };
  80816. return ArcRotateCameraVRDeviceOrientationInput;
  80817. }());
  80818. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  80819. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  80820. })(BABYLON || (BABYLON = {}));
  80821. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  80822. "use strict";
  80823. var BABYLON;
  80824. (function (BABYLON) {
  80825. var VRCameraMetrics = /** @class */ (function () {
  80826. function VRCameraMetrics() {
  80827. this.compensateDistortion = true;
  80828. }
  80829. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  80830. get: function () {
  80831. return this.hResolution / (2 * this.vResolution);
  80832. },
  80833. enumerable: true,
  80834. configurable: true
  80835. });
  80836. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  80837. get: function () {
  80838. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  80839. },
  80840. enumerable: true,
  80841. configurable: true
  80842. });
  80843. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  80844. get: function () {
  80845. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  80846. var h = (4 * meters) / this.hScreenSize;
  80847. return BABYLON.Matrix.Translation(h, 0, 0);
  80848. },
  80849. enumerable: true,
  80850. configurable: true
  80851. });
  80852. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  80853. get: function () {
  80854. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  80855. var h = (4 * meters) / this.hScreenSize;
  80856. return BABYLON.Matrix.Translation(-h, 0, 0);
  80857. },
  80858. enumerable: true,
  80859. configurable: true
  80860. });
  80861. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  80862. get: function () {
  80863. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  80864. },
  80865. enumerable: true,
  80866. configurable: true
  80867. });
  80868. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  80869. get: function () {
  80870. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  80871. },
  80872. enumerable: true,
  80873. configurable: true
  80874. });
  80875. VRCameraMetrics.GetDefault = function () {
  80876. var result = new VRCameraMetrics();
  80877. result.hResolution = 1280;
  80878. result.vResolution = 800;
  80879. result.hScreenSize = 0.149759993;
  80880. result.vScreenSize = 0.0935999975;
  80881. result.vScreenCenter = 0.0467999987;
  80882. result.eyeToScreenDistance = 0.0410000011;
  80883. result.lensSeparationDistance = 0.0635000020;
  80884. result.interpupillaryDistance = 0.0640000030;
  80885. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  80886. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  80887. result.postProcessScaleFactor = 1.714605507808412;
  80888. result.lensCenterOffset = 0.151976421;
  80889. return result;
  80890. };
  80891. return VRCameraMetrics;
  80892. }());
  80893. BABYLON.VRCameraMetrics = VRCameraMetrics;
  80894. })(BABYLON || (BABYLON = {}));
  80895. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  80896. "use strict";
  80897. var BABYLON;
  80898. (function (BABYLON) {
  80899. /**
  80900. * This represents a WebVR camera.
  80901. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  80902. * @example http://doc.babylonjs.com/how_to/webvr_camera
  80903. */
  80904. var WebVRFreeCamera = /** @class */ (function (_super) {
  80905. __extends(WebVRFreeCamera, _super);
  80906. /**
  80907. * Instantiates a WebVRFreeCamera.
  80908. * @param name The name of the WebVRFreeCamera
  80909. * @param position The starting anchor position for the camera
  80910. * @param scene The scene the camera belongs to
  80911. * @param webVROptions a set of customizable options for the webVRCamera
  80912. */
  80913. function WebVRFreeCamera(name, position, scene, webVROptions) {
  80914. if (webVROptions === void 0) { webVROptions = {}; }
  80915. var _this = _super.call(this, name, position, scene) || this;
  80916. _this.webVROptions = webVROptions;
  80917. /**
  80918. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  80919. */
  80920. _this._vrDevice = null;
  80921. /**
  80922. * The rawPose of the vrDevice.
  80923. */
  80924. _this.rawPose = null;
  80925. _this._specsVersion = "1.1";
  80926. _this._attached = false;
  80927. _this._descendants = [];
  80928. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  80929. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  80930. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  80931. _this._standingMatrix = null;
  80932. /**
  80933. * Represents device position in babylon space.
  80934. */
  80935. _this.devicePosition = BABYLON.Vector3.Zero();
  80936. /**
  80937. * Represents device rotation in babylon space.
  80938. */
  80939. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  80940. /**
  80941. * The scale of the device to be used when translating from device space to babylon space.
  80942. */
  80943. _this.deviceScaleFactor = 1;
  80944. _this._deviceToWorld = BABYLON.Matrix.Identity();
  80945. _this._worldToDevice = BABYLON.Matrix.Identity();
  80946. /**
  80947. * References to the webVR controllers for the vrDevice.
  80948. */
  80949. _this.controllers = [];
  80950. /**
  80951. * Emits an event when a controller is attached.
  80952. */
  80953. _this.onControllersAttachedObservable = new BABYLON.Observable();
  80954. /**
  80955. * Emits an event when a controller's mesh has been loaded;
  80956. */
  80957. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  80958. /**
  80959. * If the rig cameras be used as parent instead of this camera.
  80960. */
  80961. _this.rigParenting = true;
  80962. _this._defaultHeight = undefined;
  80963. _this._workingVector = BABYLON.Vector3.Zero();
  80964. _this._oneVector = BABYLON.Vector3.One();
  80965. _this._workingMatrix = BABYLON.Matrix.Identity();
  80966. _this._cache.position = BABYLON.Vector3.Zero();
  80967. if (webVROptions.defaultHeight) {
  80968. _this._defaultHeight = webVROptions.defaultHeight;
  80969. _this.position.y = _this._defaultHeight;
  80970. }
  80971. _this.minZ = 0.1;
  80972. //legacy support - the compensation boolean was removed.
  80973. if (arguments.length === 5) {
  80974. _this.webVROptions = arguments[4];
  80975. }
  80976. // default webVR options
  80977. if (_this.webVROptions.trackPosition == undefined) {
  80978. _this.webVROptions.trackPosition = true;
  80979. }
  80980. if (_this.webVROptions.controllerMeshes == undefined) {
  80981. _this.webVROptions.controllerMeshes = true;
  80982. }
  80983. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  80984. _this.webVROptions.defaultLightingOnControllers = true;
  80985. }
  80986. _this.rotationQuaternion = new BABYLON.Quaternion();
  80987. if (_this.webVROptions && _this.webVROptions.positionScale) {
  80988. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  80989. }
  80990. //enable VR
  80991. var engine = _this.getEngine();
  80992. _this._onVREnabled = function (success) { if (success) {
  80993. _this.initControllers();
  80994. } };
  80995. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  80996. engine.initWebVR().add(function (event) {
  80997. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  80998. return;
  80999. }
  81000. _this._vrDevice = event.vrDisplay;
  81001. //reset the rig parameters.
  81002. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  81003. if (_this._attached) {
  81004. _this.getEngine().enableVR();
  81005. }
  81006. });
  81007. if (typeof (VRFrameData) !== "undefined")
  81008. _this._frameData = new VRFrameData();
  81009. /**
  81010. * The idea behind the following lines:
  81011. * objects that have the camera as parent should actually have the rig cameras as a parent.
  81012. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  81013. * the second will not show it correctly.
  81014. *
  81015. * To solve this - each object that has the camera as parent will be added to a protected array.
  81016. * When the rig camera renders, it will take this array and set all of those to be its children.
  81017. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  81018. * Amazing!
  81019. */
  81020. scene.onBeforeCameraRenderObservable.add(function (camera) {
  81021. if (camera.parent === _this && _this.rigParenting) {
  81022. _this._descendants = _this.getDescendants(true, function (n) {
  81023. // don't take the cameras or the controllers!
  81024. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  81025. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  81026. return !isController && !isRigCamera;
  81027. });
  81028. _this._descendants.forEach(function (node) {
  81029. node.parent = camera;
  81030. });
  81031. }
  81032. });
  81033. scene.onAfterCameraRenderObservable.add(function (camera) {
  81034. if (camera.parent === _this && _this.rigParenting) {
  81035. _this._descendants.forEach(function (node) {
  81036. node.parent = _this;
  81037. });
  81038. }
  81039. });
  81040. return _this;
  81041. }
  81042. /**
  81043. * Gets the device distance from the ground in meters.
  81044. * @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.
  81045. */
  81046. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  81047. if (this._standingMatrix) {
  81048. // Add standing matrix offset to get real offset from ground in room
  81049. this._standingMatrix.getTranslationToRef(this._workingVector);
  81050. return this._deviceRoomPosition.y + this._workingVector.y;
  81051. }
  81052. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  81053. return this._defaultHeight || 0;
  81054. };
  81055. /**
  81056. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  81057. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  81058. */
  81059. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  81060. var _this = this;
  81061. if (callback === void 0) { callback = function (bool) { }; }
  81062. // Use standing matrix if available
  81063. this.getEngine().initWebVRAsync().then(function (result) {
  81064. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  81065. callback(false);
  81066. }
  81067. else {
  81068. _this._standingMatrix = new BABYLON.Matrix();
  81069. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  81070. if (!_this.getScene().useRightHandedSystem) {
  81071. [2, 6, 8, 9, 14].forEach(function (num) {
  81072. if (_this._standingMatrix) {
  81073. _this._standingMatrix.m[num] *= -1;
  81074. }
  81075. });
  81076. }
  81077. callback(true);
  81078. }
  81079. });
  81080. };
  81081. /**
  81082. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  81083. * @returns A promise with a boolean set to if the standing matrix is supported.
  81084. */
  81085. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  81086. var _this = this;
  81087. return new Promise(function (res, rej) {
  81088. _this.useStandingMatrix(function (supported) {
  81089. res(supported);
  81090. });
  81091. });
  81092. };
  81093. /**
  81094. * Disposes the camera
  81095. */
  81096. WebVRFreeCamera.prototype.dispose = function () {
  81097. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  81098. _super.prototype.dispose.call(this);
  81099. };
  81100. /**
  81101. * Gets a vrController by name.
  81102. * @param name The name of the controller to retreive
  81103. * @returns the controller matching the name specified or null if not found
  81104. */
  81105. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  81106. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  81107. var gp = _a[_i];
  81108. if (gp.hand === name) {
  81109. return gp;
  81110. }
  81111. }
  81112. return null;
  81113. };
  81114. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  81115. /**
  81116. * The controller corrisponding to the users left hand.
  81117. */
  81118. get: function () {
  81119. if (!this._leftController) {
  81120. this._leftController = this.getControllerByName("left");
  81121. }
  81122. return this._leftController;
  81123. },
  81124. enumerable: true,
  81125. configurable: true
  81126. });
  81127. ;
  81128. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  81129. /**
  81130. * The controller corrisponding to the users right hand.
  81131. */
  81132. get: function () {
  81133. if (!this._rightController) {
  81134. this._rightController = this.getControllerByName("right");
  81135. }
  81136. return this._rightController;
  81137. },
  81138. enumerable: true,
  81139. configurable: true
  81140. });
  81141. ;
  81142. /**
  81143. * Casts a ray forward from the vrCamera's gaze.
  81144. * @param length Length of the ray (default: 100)
  81145. * @returns the ray corrisponding to the gaze
  81146. */
  81147. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  81148. if (length === void 0) { length = 100; }
  81149. if (this.leftCamera) {
  81150. // Use left eye to avoid computation to compute center on every call
  81151. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  81152. }
  81153. else {
  81154. return _super.prototype.getForwardRay.call(this, length);
  81155. }
  81156. };
  81157. /**
  81158. * Updates the camera based on device's frame data
  81159. */
  81160. WebVRFreeCamera.prototype._checkInputs = function () {
  81161. if (this._vrDevice && this._vrDevice.isPresenting) {
  81162. this._vrDevice.getFrameData(this._frameData);
  81163. this.updateFromDevice(this._frameData.pose);
  81164. }
  81165. _super.prototype._checkInputs.call(this);
  81166. };
  81167. /**
  81168. * Updates the poseControlled values based on the input device pose.
  81169. * @param poseData Pose coming from the device
  81170. */
  81171. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  81172. if (poseData && poseData.orientation) {
  81173. this.rawPose = poseData;
  81174. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  81175. if (this.getScene().useRightHandedSystem) {
  81176. this._deviceRoomRotationQuaternion.z *= -1;
  81177. this._deviceRoomRotationQuaternion.w *= -1;
  81178. }
  81179. if (this.webVROptions.trackPosition && this.rawPose.position) {
  81180. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  81181. if (this.getScene().useRightHandedSystem) {
  81182. this._deviceRoomPosition.z *= -1;
  81183. }
  81184. }
  81185. }
  81186. };
  81187. /**
  81188. * WebVR's attach control will start broadcasting frames to the device.
  81189. * Note that in certain browsers (chrome for example) this function must be called
  81190. * within a user-interaction callback. Example:
  81191. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  81192. *
  81193. * @param element html element to attach the vrDevice to
  81194. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  81195. */
  81196. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  81197. _super.prototype.attachControl.call(this, element, noPreventDefault);
  81198. this._attached = true;
  81199. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  81200. if (this._vrDevice) {
  81201. this.getEngine().enableVR();
  81202. }
  81203. };
  81204. /**
  81205. * Detaches the camera from the html element and disables VR
  81206. *
  81207. * @param element html element to detach from
  81208. */
  81209. WebVRFreeCamera.prototype.detachControl = function (element) {
  81210. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  81211. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  81212. _super.prototype.detachControl.call(this, element);
  81213. this._attached = false;
  81214. this.getEngine().disableVR();
  81215. };
  81216. /**
  81217. * @returns the name of this class
  81218. */
  81219. WebVRFreeCamera.prototype.getClassName = function () {
  81220. return "WebVRFreeCamera";
  81221. };
  81222. /**
  81223. * Calls resetPose on the vrDisplay
  81224. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  81225. */
  81226. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  81227. //uses the vrDisplay's "resetPose()".
  81228. //pitch and roll won't be affected.
  81229. this._vrDevice.resetPose();
  81230. };
  81231. /**
  81232. * Updates the rig cameras (left and right eye)
  81233. */
  81234. WebVRFreeCamera.prototype._updateRigCameras = function () {
  81235. var camLeft = this._rigCameras[0];
  81236. var camRight = this._rigCameras[1];
  81237. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  81238. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  81239. camLeft.position.copyFrom(this._deviceRoomPosition);
  81240. camRight.position.copyFrom(this._deviceRoomPosition);
  81241. };
  81242. /**
  81243. * Updates the cached values of the camera
  81244. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  81245. */
  81246. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  81247. var _this = this;
  81248. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  81249. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  81250. if (!this.updateCacheCalled) {
  81251. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  81252. this.updateCacheCalled = true;
  81253. this.update();
  81254. }
  81255. // Set working vector to the device position in room space rotated by the new rotation
  81256. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  81257. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  81258. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  81259. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  81260. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  81261. // Add translation from anchor position
  81262. this._deviceToWorld.getTranslationToRef(this._workingVector);
  81263. this._workingVector.addInPlace(this.position);
  81264. this._workingVector.subtractInPlace(this._cache.position);
  81265. this._deviceToWorld.setTranslation(this._workingVector);
  81266. // Set an inverted matrix to be used when updating the camera
  81267. this._deviceToWorld.invertToRef(this._worldToDevice);
  81268. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  81269. this.controllers.forEach(function (controller) {
  81270. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  81271. controller.update();
  81272. });
  81273. }
  81274. if (!ignoreParentClass) {
  81275. _super.prototype._updateCache.call(this);
  81276. }
  81277. this.updateCacheCalled = false;
  81278. };
  81279. /**
  81280. * Updates the current device position and rotation in the babylon world
  81281. */
  81282. WebVRFreeCamera.prototype.update = function () {
  81283. // Get current device position in babylon world
  81284. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  81285. // Get current device rotation in babylon world
  81286. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  81287. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  81288. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  81289. _super.prototype.update.call(this);
  81290. };
  81291. /**
  81292. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  81293. * @returns an identity matrix
  81294. */
  81295. WebVRFreeCamera.prototype._getViewMatrix = function () {
  81296. return BABYLON.Matrix.Identity();
  81297. };
  81298. /**
  81299. * This function is called by the two RIG cameras.
  81300. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  81301. */
  81302. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  81303. var _this = this;
  81304. // Update the parent camera prior to using a child camera to avoid desynchronization
  81305. var parentCamera = this._cameraRigParams["parentCamera"];
  81306. parentCamera._updateCache();
  81307. //WebVR 1.1
  81308. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  81309. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  81310. if (!this.getScene().useRightHandedSystem) {
  81311. [2, 6, 8, 9, 14].forEach(function (num) {
  81312. _this._webvrViewMatrix.m[num] *= -1;
  81313. });
  81314. }
  81315. // update the camera rotation matrix
  81316. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  81317. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  81318. // Computing target and final matrix
  81319. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  81320. // should the view matrix be updated with scale and position offset?
  81321. if (parentCamera.deviceScaleFactor !== 1) {
  81322. this._webvrViewMatrix.invert();
  81323. // scale the position, if set
  81324. if (parentCamera.deviceScaleFactor) {
  81325. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  81326. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  81327. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  81328. }
  81329. this._webvrViewMatrix.invert();
  81330. }
  81331. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  81332. return this._webvrViewMatrix;
  81333. };
  81334. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  81335. var _this = this;
  81336. var parentCamera = this.parent;
  81337. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  81338. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  81339. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  81340. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  81341. //babylon compatible matrix
  81342. if (!this.getScene().useRightHandedSystem) {
  81343. [8, 9, 10, 11].forEach(function (num) {
  81344. _this._projectionMatrix.m[num] *= -1;
  81345. });
  81346. }
  81347. return this._projectionMatrix;
  81348. };
  81349. /**
  81350. * Initializes the controllers and their meshes
  81351. */
  81352. WebVRFreeCamera.prototype.initControllers = function () {
  81353. var _this = this;
  81354. this.controllers = [];
  81355. var manager = this.getScene().gamepadManager;
  81356. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  81357. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  81358. var webVrController = gamepad;
  81359. if (webVrController.defaultModel) {
  81360. webVrController.defaultModel.setEnabled(false);
  81361. }
  81362. if (webVrController.hand === "right") {
  81363. _this._rightController = null;
  81364. }
  81365. if (webVrController.hand === "left") {
  81366. _this._leftController = null;
  81367. }
  81368. var controllerIndex = _this.controllers.indexOf(webVrController);
  81369. if (controllerIndex !== -1) {
  81370. _this.controllers.splice(controllerIndex, 1);
  81371. }
  81372. }
  81373. });
  81374. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  81375. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  81376. var webVrController_1 = gamepad;
  81377. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  81378. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  81379. if (_this.webVROptions.controllerMeshes) {
  81380. if (webVrController_1.defaultModel) {
  81381. webVrController_1.defaultModel.setEnabled(true);
  81382. }
  81383. else {
  81384. // Load the meshes
  81385. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  81386. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  81387. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  81388. if (_this.webVROptions.defaultLightingOnControllers) {
  81389. if (!_this._lightOnControllers) {
  81390. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  81391. }
  81392. var activateLightOnSubMeshes_1 = function (mesh, light) {
  81393. var children = mesh.getChildren();
  81394. if (children.length !== 0) {
  81395. children.forEach(function (mesh) {
  81396. light.includedOnlyMeshes.push(mesh);
  81397. activateLightOnSubMeshes_1(mesh, light);
  81398. });
  81399. }
  81400. };
  81401. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  81402. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  81403. }
  81404. });
  81405. }
  81406. }
  81407. webVrController_1.attachToPoseControlledCamera(_this);
  81408. // since this is async - sanity check. Is the controller already stored?
  81409. if (_this.controllers.indexOf(webVrController_1) === -1) {
  81410. //add to the controllers array
  81411. _this.controllers.push(webVrController_1);
  81412. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  81413. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  81414. // So we're overriding setting left & right manually to be sure
  81415. var firstViveWandDetected = false;
  81416. for (var i = 0; i < _this.controllers.length; i++) {
  81417. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  81418. if (!firstViveWandDetected) {
  81419. firstViveWandDetected = true;
  81420. _this.controllers[i].hand = "left";
  81421. }
  81422. else {
  81423. _this.controllers[i].hand = "right";
  81424. }
  81425. }
  81426. }
  81427. //did we find enough controllers? Great! let the developer know.
  81428. if (_this.controllers.length >= 2) {
  81429. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  81430. }
  81431. }
  81432. }
  81433. });
  81434. };
  81435. return WebVRFreeCamera;
  81436. }(BABYLON.FreeCamera));
  81437. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  81438. })(BABYLON || (BABYLON = {}));
  81439. //# sourceMappingURL=babylon.webVRCamera.js.map
  81440. "use strict";
  81441. var BABYLON;
  81442. (function (BABYLON) {
  81443. // We're mainly based on the logic defined into the FreeCamera code
  81444. /**
  81445. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  81446. * being tilted forward or back and left or right.
  81447. */
  81448. var DeviceOrientationCamera = /** @class */ (function (_super) {
  81449. __extends(DeviceOrientationCamera, _super);
  81450. /**
  81451. * Creates a new device orientation camera. @see DeviceOrientationCamera
  81452. * @param name The name of the camera
  81453. * @param position The start position camera
  81454. * @param scene The scene the camera belongs to
  81455. */
  81456. function DeviceOrientationCamera(name, position, scene) {
  81457. var _this = _super.call(this, name, position, scene) || this;
  81458. _this._quaternionCache = new BABYLON.Quaternion();
  81459. _this.inputs.addDeviceOrientation();
  81460. return _this;
  81461. }
  81462. /**
  81463. * Gets the current instance class name ("DeviceOrientationCamera").
  81464. * This helps avoiding instanceof at run time.
  81465. * @returns the class name
  81466. */
  81467. DeviceOrientationCamera.prototype.getClassName = function () {
  81468. return "DeviceOrientationCamera";
  81469. };
  81470. /**
  81471. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  81472. */
  81473. DeviceOrientationCamera.prototype._checkInputs = function () {
  81474. _super.prototype._checkInputs.call(this);
  81475. this._quaternionCache.copyFrom(this.rotationQuaternion);
  81476. if (this._initialQuaternion) {
  81477. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  81478. }
  81479. };
  81480. /**
  81481. * Reset the camera to its default orientation on the specified axis only.
  81482. * @param axis The axis to reset
  81483. */
  81484. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  81485. var _this = this;
  81486. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  81487. //can only work if this camera has a rotation quaternion already.
  81488. if (!this.rotationQuaternion)
  81489. return;
  81490. if (!this._initialQuaternion) {
  81491. this._initialQuaternion = new BABYLON.Quaternion();
  81492. }
  81493. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  81494. ['x', 'y', 'z'].forEach(function (axisName) {
  81495. if (!axis[axisName]) {
  81496. _this._initialQuaternion[axisName] = 0;
  81497. }
  81498. else {
  81499. _this._initialQuaternion[axisName] *= -1;
  81500. }
  81501. });
  81502. this._initialQuaternion.normalize();
  81503. //force rotation update
  81504. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  81505. };
  81506. return DeviceOrientationCamera;
  81507. }(BABYLON.FreeCamera));
  81508. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  81509. })(BABYLON || (BABYLON = {}));
  81510. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  81511. "use strict";
  81512. var BABYLON;
  81513. (function (BABYLON) {
  81514. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  81515. __extends(VRDeviceOrientationFreeCamera, _super);
  81516. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  81517. if (compensateDistortion === void 0) { compensateDistortion = true; }
  81518. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  81519. var _this = _super.call(this, name, position, scene) || this;
  81520. vrCameraMetrics.compensateDistortion = compensateDistortion;
  81521. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  81522. return _this;
  81523. }
  81524. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  81525. return "VRDeviceOrientationFreeCamera";
  81526. };
  81527. return VRDeviceOrientationFreeCamera;
  81528. }(BABYLON.DeviceOrientationCamera));
  81529. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  81530. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  81531. __extends(VRDeviceOrientationGamepadCamera, _super);
  81532. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  81533. if (compensateDistortion === void 0) { compensateDistortion = true; }
  81534. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  81535. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  81536. _this.inputs.addGamepad();
  81537. return _this;
  81538. }
  81539. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  81540. return "VRDeviceOrientationGamepadCamera";
  81541. };
  81542. return VRDeviceOrientationGamepadCamera;
  81543. }(VRDeviceOrientationFreeCamera));
  81544. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  81545. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  81546. __extends(VRDeviceOrientationArcRotateCamera, _super);
  81547. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  81548. if (compensateDistortion === void 0) { compensateDistortion = true; }
  81549. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  81550. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  81551. vrCameraMetrics.compensateDistortion = compensateDistortion;
  81552. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  81553. _this.inputs.addVRDeviceOrientation();
  81554. return _this;
  81555. }
  81556. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  81557. return "VRDeviceOrientationArcRotateCamera";
  81558. };
  81559. return VRDeviceOrientationArcRotateCamera;
  81560. }(BABYLON.ArcRotateCamera));
  81561. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  81562. })(BABYLON || (BABYLON = {}));
  81563. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  81564. "use strict";
  81565. var BABYLON;
  81566. (function (BABYLON) {
  81567. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  81568. __extends(AnaglyphFreeCamera, _super);
  81569. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  81570. var _this = _super.call(this, name, position, scene) || this;
  81571. _this.interaxialDistance = interaxialDistance;
  81572. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81573. return _this;
  81574. }
  81575. AnaglyphFreeCamera.prototype.getClassName = function () {
  81576. return "AnaglyphFreeCamera";
  81577. };
  81578. return AnaglyphFreeCamera;
  81579. }(BABYLON.FreeCamera));
  81580. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  81581. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  81582. __extends(AnaglyphArcRotateCamera, _super);
  81583. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  81584. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  81585. _this.interaxialDistance = interaxialDistance;
  81586. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81587. return _this;
  81588. }
  81589. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  81590. return "AnaglyphArcRotateCamera";
  81591. };
  81592. return AnaglyphArcRotateCamera;
  81593. }(BABYLON.ArcRotateCamera));
  81594. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  81595. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  81596. __extends(AnaglyphGamepadCamera, _super);
  81597. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  81598. var _this = _super.call(this, name, position, scene) || this;
  81599. _this.interaxialDistance = interaxialDistance;
  81600. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81601. return _this;
  81602. }
  81603. AnaglyphGamepadCamera.prototype.getClassName = function () {
  81604. return "AnaglyphGamepadCamera";
  81605. };
  81606. return AnaglyphGamepadCamera;
  81607. }(BABYLON.GamepadCamera));
  81608. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  81609. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  81610. __extends(AnaglyphUniversalCamera, _super);
  81611. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  81612. var _this = _super.call(this, name, position, scene) || this;
  81613. _this.interaxialDistance = interaxialDistance;
  81614. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81615. return _this;
  81616. }
  81617. AnaglyphUniversalCamera.prototype.getClassName = function () {
  81618. return "AnaglyphUniversalCamera";
  81619. };
  81620. return AnaglyphUniversalCamera;
  81621. }(BABYLON.UniversalCamera));
  81622. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  81623. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  81624. __extends(StereoscopicFreeCamera, _super);
  81625. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  81626. var _this = _super.call(this, name, position, scene) || this;
  81627. _this.interaxialDistance = interaxialDistance;
  81628. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81629. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81630. return _this;
  81631. }
  81632. StereoscopicFreeCamera.prototype.getClassName = function () {
  81633. return "StereoscopicFreeCamera";
  81634. };
  81635. return StereoscopicFreeCamera;
  81636. }(BABYLON.FreeCamera));
  81637. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  81638. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  81639. __extends(StereoscopicArcRotateCamera, _super);
  81640. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  81641. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  81642. _this.interaxialDistance = interaxialDistance;
  81643. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81644. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81645. return _this;
  81646. }
  81647. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  81648. return "StereoscopicArcRotateCamera";
  81649. };
  81650. return StereoscopicArcRotateCamera;
  81651. }(BABYLON.ArcRotateCamera));
  81652. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  81653. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  81654. __extends(StereoscopicGamepadCamera, _super);
  81655. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  81656. var _this = _super.call(this, name, position, scene) || this;
  81657. _this.interaxialDistance = interaxialDistance;
  81658. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81659. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81660. return _this;
  81661. }
  81662. StereoscopicGamepadCamera.prototype.getClassName = function () {
  81663. return "StereoscopicGamepadCamera";
  81664. };
  81665. return StereoscopicGamepadCamera;
  81666. }(BABYLON.GamepadCamera));
  81667. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  81668. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  81669. __extends(StereoscopicUniversalCamera, _super);
  81670. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  81671. var _this = _super.call(this, name, position, scene) || this;
  81672. _this.interaxialDistance = interaxialDistance;
  81673. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81674. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81675. return _this;
  81676. }
  81677. StereoscopicUniversalCamera.prototype.getClassName = function () {
  81678. return "StereoscopicUniversalCamera";
  81679. };
  81680. return StereoscopicUniversalCamera;
  81681. }(BABYLON.UniversalCamera));
  81682. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  81683. })(BABYLON || (BABYLON = {}));
  81684. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  81685. "use strict";
  81686. var BABYLON;
  81687. (function (BABYLON) {
  81688. var VRExperienceHelperGazer = /** @class */ (function () {
  81689. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  81690. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  81691. this.scene = scene;
  81692. this._pointerDownOnMeshAsked = false;
  81693. this._isActionableMesh = false;
  81694. this._teleportationRequestInitiated = false;
  81695. this._teleportationBackRequestInitiated = false;
  81696. this._dpadPressed = true;
  81697. this._activePointer = false;
  81698. this._id = VRExperienceHelperGazer._idCounter++;
  81699. // Gaze tracker
  81700. if (!gazeTrackerToClone) {
  81701. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  81702. this._gazeTracker.bakeCurrentTransformIntoVertices();
  81703. this._gazeTracker.isPickable = false;
  81704. this._gazeTracker.isVisible = false;
  81705. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  81706. targetMat.specularColor = BABYLON.Color3.Black();
  81707. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  81708. targetMat.backFaceCulling = false;
  81709. this._gazeTracker.material = targetMat;
  81710. }
  81711. else {
  81712. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  81713. }
  81714. }
  81715. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  81716. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  81717. };
  81718. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  81719. this._pointerDownOnMeshAsked = true;
  81720. if (this._currentMeshSelected && this._currentHit) {
  81721. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  81722. }
  81723. };
  81724. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  81725. if (this._currentMeshSelected && this._currentHit) {
  81726. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  81727. }
  81728. this._pointerDownOnMeshAsked = false;
  81729. };
  81730. VRExperienceHelperGazer.prototype._activatePointer = function () {
  81731. this._activePointer = true;
  81732. };
  81733. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  81734. this._activePointer = false;
  81735. };
  81736. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  81737. };
  81738. VRExperienceHelperGazer.prototype.dispose = function () {
  81739. this._interactionsEnabled = false;
  81740. this._teleportationEnabled = false;
  81741. };
  81742. VRExperienceHelperGazer._idCounter = 0;
  81743. return VRExperienceHelperGazer;
  81744. }());
  81745. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  81746. __extends(VRExperienceHelperControllerGazer, _super);
  81747. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  81748. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  81749. _this.webVRController = webVRController;
  81750. // Laser pointer
  81751. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  81752. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  81753. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  81754. laserPointerMaterial.alpha = 0.6;
  81755. _this._laserPointer.material = laserPointerMaterial;
  81756. _this._laserPointer.rotation.x = Math.PI / 2;
  81757. _this._laserPointer.position.z = -0.5;
  81758. _this._laserPointer.isVisible = false;
  81759. if (!webVRController.mesh) {
  81760. // Create an empty mesh that is used prior to loading the high quality model
  81761. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  81762. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  81763. preloadPointerPose.rotation.x = -0.7;
  81764. preloadMesh.addChild(preloadPointerPose);
  81765. webVRController.attachToMesh(preloadMesh);
  81766. }
  81767. _this._setLaserPointerParent(webVRController.mesh);
  81768. return _this;
  81769. }
  81770. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  81771. return this.webVRController.getForwardRay(length);
  81772. };
  81773. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  81774. _super.prototype._activatePointer.call(this);
  81775. this._laserPointer.isVisible = true;
  81776. };
  81777. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  81778. _super.prototype._deactivatePointer.call(this);
  81779. this._laserPointer.isVisible = false;
  81780. };
  81781. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  81782. this._laserPointer.material.emissiveColor = color;
  81783. };
  81784. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  81785. var makeNotPick = function (root) {
  81786. root.name += " laserPointer";
  81787. root.getChildMeshes().forEach(function (c) {
  81788. makeNotPick(c);
  81789. });
  81790. };
  81791. makeNotPick(mesh);
  81792. var childMeshes = mesh.getChildMeshes();
  81793. this.webVRController._pointingPoseNode = null;
  81794. for (var i = 0; i < childMeshes.length; i++) {
  81795. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  81796. mesh = childMeshes[i];
  81797. this.webVRController._pointingPoseNode = mesh;
  81798. break;
  81799. }
  81800. }
  81801. this._laserPointer.parent = mesh;
  81802. };
  81803. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  81804. this._laserPointer.scaling.y = distance;
  81805. this._laserPointer.position.z = -distance / 2;
  81806. };
  81807. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  81808. _super.prototype.dispose.call(this);
  81809. this._laserPointer.dispose();
  81810. };
  81811. return VRExperienceHelperControllerGazer;
  81812. }(VRExperienceHelperGazer));
  81813. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  81814. __extends(VRExperienceHelperCameraGazer, _super);
  81815. function VRExperienceHelperCameraGazer(getCamera, scene) {
  81816. var _this = _super.call(this, scene) || this;
  81817. _this.getCamera = getCamera;
  81818. return _this;
  81819. }
  81820. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  81821. var camera = this.getCamera();
  81822. if (camera) {
  81823. return camera.getForwardRay(length);
  81824. }
  81825. else {
  81826. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  81827. }
  81828. };
  81829. return VRExperienceHelperCameraGazer;
  81830. }(VRExperienceHelperGazer));
  81831. /**
  81832. * Helps to quickly add VR support to an existing scene.
  81833. * See http://doc.babylonjs.com/how_to/webvr_helper
  81834. */
  81835. var VRExperienceHelper = /** @class */ (function () {
  81836. /**
  81837. * Instantiates a VRExperienceHelper.
  81838. * Helps to quickly add VR support to an existing scene.
  81839. * @param scene The scene the VRExperienceHelper belongs to.
  81840. * @param webVROptions Options to modify the vr experience helper's behavior.
  81841. */
  81842. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  81843. if (webVROptions === void 0) { webVROptions = {}; }
  81844. var _this = this;
  81845. this.webVROptions = webVROptions;
  81846. // Can the system support WebVR, even if a headset isn't plugged in?
  81847. this._webVRsupported = false;
  81848. // If WebVR is supported, is a headset plugged in and are we ready to present?
  81849. this._webVRready = false;
  81850. // Are we waiting for the requestPresent callback to complete?
  81851. this._webVRrequesting = false;
  81852. // Are we presenting to the headset right now?
  81853. this._webVRpresenting = false;
  81854. // Are we presenting in the fullscreen fallback?
  81855. this._fullscreenVRpresenting = false;
  81856. /**
  81857. * Observable raised when entering VR.
  81858. */
  81859. this.onEnteringVRObservable = new BABYLON.Observable();
  81860. /**
  81861. * Observable raised when exiting VR.
  81862. */
  81863. this.onExitingVRObservable = new BABYLON.Observable();
  81864. /**
  81865. * Observable raised when controller mesh is loaded.
  81866. */
  81867. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  81868. this._useCustomVRButton = false;
  81869. this._teleportationRequested = false;
  81870. this._teleportActive = false;
  81871. this._floorMeshesCollection = [];
  81872. this._rotationAllowed = true;
  81873. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  81874. this._rotationRightAsked = false;
  81875. this._rotationLeftAsked = false;
  81876. this._isDefaultTeleportationTarget = true;
  81877. this._teleportationFillColor = "#444444";
  81878. this._teleportationBorderColor = "#FFFFFF";
  81879. this._rotationAngle = 0;
  81880. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  81881. this._padSensibilityUp = 0.65;
  81882. this._padSensibilityDown = 0.35;
  81883. this.leftController = null;
  81884. this.rightController = null;
  81885. /**
  81886. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  81887. */
  81888. this.onNewMeshSelected = new BABYLON.Observable();
  81889. /**
  81890. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  81891. */
  81892. this.onNewMeshPicked = new BABYLON.Observable();
  81893. /**
  81894. * Observable raised before camera teleportation
  81895. */
  81896. this.onBeforeCameraTeleport = new BABYLON.Observable();
  81897. /**
  81898. * Observable raised after camera teleportation
  81899. */
  81900. this.onAfterCameraTeleport = new BABYLON.Observable();
  81901. /**
  81902. * Observable raised when current selected mesh gets unselected
  81903. */
  81904. this.onSelectedMeshUnselected = new BABYLON.Observable();
  81905. /**
  81906. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  81907. */
  81908. this.teleportationEnabled = true;
  81909. this._teleportationInitialized = false;
  81910. this._interactionsEnabled = false;
  81911. this._interactionsRequested = false;
  81912. this._displayGaze = true;
  81913. this._displayLaserPointer = true;
  81914. this._onResize = function () {
  81915. _this.moveButtonToBottomRight();
  81916. if (_this._fullscreenVRpresenting && _this._webVRready) {
  81917. _this.exitVR();
  81918. }
  81919. };
  81920. this._onFullscreenChange = function () {
  81921. if (document.fullscreen !== undefined) {
  81922. _this._fullscreenVRpresenting = document.fullscreen;
  81923. }
  81924. else if (document.mozFullScreen !== undefined) {
  81925. _this._fullscreenVRpresenting = document.mozFullScreen;
  81926. }
  81927. else if (document.webkitIsFullScreen !== undefined) {
  81928. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  81929. }
  81930. else if (document.msIsFullScreen !== undefined) {
  81931. _this._fullscreenVRpresenting = document.msIsFullScreen;
  81932. }
  81933. if (!_this._fullscreenVRpresenting && _this._canvas) {
  81934. _this.exitVR();
  81935. if (!_this._useCustomVRButton) {
  81936. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  81937. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  81938. }
  81939. }
  81940. };
  81941. this.beforeRender = function () {
  81942. if (_this.leftController && _this.leftController._activePointer) {
  81943. _this._castRayAndSelectObject(_this.leftController);
  81944. }
  81945. if (_this.rightController && _this.rightController._activePointer) {
  81946. _this._castRayAndSelectObject(_this.rightController);
  81947. }
  81948. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  81949. _this._castRayAndSelectObject(_this._cameraGazer);
  81950. }
  81951. else {
  81952. _this._cameraGazer._gazeTracker.isVisible = false;
  81953. }
  81954. };
  81955. this._onNewGamepadConnected = function (gamepad) {
  81956. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  81957. if (gamepad.leftStick) {
  81958. gamepad.onleftstickchanged(function (stickValues) {
  81959. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  81960. // Listening to classic/xbox gamepad only if no VR controller is active
  81961. if ((!_this.leftController && !_this.rightController) ||
  81962. ((_this.leftController && !_this.leftController._activePointer) &&
  81963. (_this.rightController && !_this.rightController._activePointer))) {
  81964. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  81965. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  81966. }
  81967. }
  81968. });
  81969. }
  81970. if (gamepad.rightStick) {
  81971. gamepad.onrightstickchanged(function (stickValues) {
  81972. if (_this._teleportationInitialized) {
  81973. _this._checkRotate(stickValues, _this._cameraGazer);
  81974. }
  81975. });
  81976. }
  81977. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  81978. gamepad.onbuttondown(function (buttonPressed) {
  81979. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  81980. _this._cameraGazer._selectionPointerDown();
  81981. }
  81982. });
  81983. gamepad.onbuttonup(function (buttonPressed) {
  81984. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  81985. _this._cameraGazer._selectionPointerUp();
  81986. }
  81987. });
  81988. }
  81989. }
  81990. else {
  81991. var webVRController = gamepad;
  81992. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  81993. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  81994. _this.rightController = controller;
  81995. }
  81996. else {
  81997. _this.leftController = controller;
  81998. }
  81999. _this._tryEnableInteractionOnController(controller);
  82000. }
  82001. };
  82002. // 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
  82003. this._tryEnableInteractionOnController = function (controller) {
  82004. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  82005. _this._enableInteractionOnController(controller);
  82006. }
  82007. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  82008. _this._enableTeleportationOnController(controller);
  82009. }
  82010. };
  82011. this._onNewGamepadDisconnected = function (gamepad) {
  82012. if (gamepad instanceof BABYLON.WebVRController) {
  82013. if (gamepad.hand === "left" && _this.leftController != null) {
  82014. _this.leftController.dispose();
  82015. _this.leftController = null;
  82016. }
  82017. if (gamepad.hand === "right" && _this.rightController != null) {
  82018. _this.rightController.dispose();
  82019. _this.rightController = null;
  82020. }
  82021. }
  82022. };
  82023. this._workingVector = BABYLON.Vector3.Zero();
  82024. this._workingQuaternion = BABYLON.Quaternion.Identity();
  82025. this._workingMatrix = BABYLON.Matrix.Identity();
  82026. this._scene = scene;
  82027. this._canvas = scene.getEngine().getRenderingCanvas();
  82028. // Parse options
  82029. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  82030. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  82031. }
  82032. if (webVROptions.createDeviceOrientationCamera === undefined) {
  82033. webVROptions.createDeviceOrientationCamera = true;
  82034. }
  82035. if (webVROptions.defaultHeight === undefined) {
  82036. webVROptions.defaultHeight = 1.7;
  82037. }
  82038. if (webVROptions.useCustomVRButton) {
  82039. this._useCustomVRButton = true;
  82040. if (webVROptions.customVRButton) {
  82041. this._btnVR = webVROptions.customVRButton;
  82042. }
  82043. }
  82044. if (webVROptions.rayLength) {
  82045. this._rayLength = webVROptions.rayLength;
  82046. }
  82047. this._defaultHeight = webVROptions.defaultHeight;
  82048. if (webVROptions.positionScale) {
  82049. this._rayLength *= webVROptions.positionScale;
  82050. this._defaultHeight *= webVROptions.positionScale;
  82051. }
  82052. // Set position
  82053. if (this._scene.activeCamera) {
  82054. this._position = this._scene.activeCamera.position.clone();
  82055. }
  82056. else {
  82057. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  82058. }
  82059. // Set non-vr camera
  82060. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  82061. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  82062. // Copy data from existing camera
  82063. if (this._scene.activeCamera) {
  82064. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  82065. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  82066. // Set rotation from previous camera
  82067. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  82068. var targetCamera = this._scene.activeCamera;
  82069. if (targetCamera.rotationQuaternion) {
  82070. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  82071. }
  82072. else {
  82073. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  82074. }
  82075. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  82076. }
  82077. }
  82078. this._scene.activeCamera = this._deviceOrientationCamera;
  82079. if (this._canvas) {
  82080. this._scene.activeCamera.attachControl(this._canvas);
  82081. }
  82082. }
  82083. else {
  82084. this._existingCamera = this._scene.activeCamera;
  82085. }
  82086. // Create VR cameras
  82087. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  82088. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  82089. }
  82090. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  82091. this._webVRCamera.useStandingMatrix();
  82092. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  82093. // Create default button
  82094. if (!this._useCustomVRButton) {
  82095. this._btnVR = document.createElement("BUTTON");
  82096. this._btnVR.className = "babylonVRicon";
  82097. this._btnVR.id = "babylonVRiconbtn";
  82098. this._btnVR.title = "Click to switch to VR";
  82099. 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) }";
  82100. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  82101. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  82102. // css += ".babylonVRicon.vrdisplaysupported { }";
  82103. // css += ".babylonVRicon.vrdisplayready { }";
  82104. // css += ".babylonVRicon.vrdisplayrequesting { }";
  82105. var style = document.createElement('style');
  82106. style.appendChild(document.createTextNode(css));
  82107. document.getElementsByTagName('head')[0].appendChild(style);
  82108. this.moveButtonToBottomRight();
  82109. }
  82110. // VR button click event
  82111. if (this._btnVR) {
  82112. this._btnVR.addEventListener("click", function () {
  82113. if (!_this.isInVRMode) {
  82114. _this.enterVR();
  82115. }
  82116. else {
  82117. _this.exitVR();
  82118. }
  82119. });
  82120. }
  82121. // Window events
  82122. window.addEventListener("resize", this._onResize);
  82123. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  82124. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  82125. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  82126. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  82127. // Display vr button when headset is connected
  82128. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  82129. this.displayVRButton();
  82130. }
  82131. else {
  82132. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  82133. if (e.vrDisplay) {
  82134. _this.displayVRButton();
  82135. }
  82136. });
  82137. }
  82138. // Exiting VR mode using 'ESC' key on desktop
  82139. this._onKeyDown = function (event) {
  82140. if (event.keyCode === 27 && _this.isInVRMode) {
  82141. _this.exitVR();
  82142. }
  82143. };
  82144. document.addEventListener("keydown", this._onKeyDown);
  82145. // Exiting VR mode double tapping the touch screen
  82146. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  82147. if (_this.isInVRMode) {
  82148. _this.exitVR();
  82149. if (_this._fullscreenVRpresenting) {
  82150. _this._scene.getEngine().switchFullscreen(true);
  82151. }
  82152. }
  82153. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  82154. // Listen for WebVR display changes
  82155. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  82156. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  82157. this._onVRRequestPresentStart = function () {
  82158. _this._webVRrequesting = true;
  82159. _this.updateButtonVisibility();
  82160. };
  82161. this._onVRRequestPresentComplete = function (success) {
  82162. _this._webVRrequesting = false;
  82163. _this.updateButtonVisibility();
  82164. };
  82165. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  82166. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  82167. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  82168. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82169. scene.onDisposeObservable.add(function () {
  82170. _this.dispose();
  82171. });
  82172. // Gamepad connection events
  82173. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  82174. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  82175. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  82176. this.updateButtonVisibility();
  82177. //create easing functions
  82178. this._circleEase = new BABYLON.CircleEase();
  82179. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  82180. }
  82181. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  82182. /** Return this.onEnteringVRObservable
  82183. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  82184. */
  82185. get: function () {
  82186. return this.onEnteringVRObservable;
  82187. },
  82188. enumerable: true,
  82189. configurable: true
  82190. });
  82191. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  82192. /** Return this.onExitingVRObservable
  82193. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  82194. */
  82195. get: function () {
  82196. return this.onExitingVRObservable;
  82197. },
  82198. enumerable: true,
  82199. configurable: true
  82200. });
  82201. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  82202. /** Return this.onControllerMeshLoadedObservable
  82203. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  82204. */
  82205. get: function () {
  82206. return this.onControllerMeshLoadedObservable;
  82207. },
  82208. enumerable: true,
  82209. configurable: true
  82210. });
  82211. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  82212. /**
  82213. * The mesh used to display where the user is going to teleport.
  82214. */
  82215. get: function () {
  82216. return this._teleportationTarget;
  82217. },
  82218. /**
  82219. * Sets the mesh to be used to display where the user is going to teleport.
  82220. */
  82221. set: function (value) {
  82222. if (value) {
  82223. value.name = "teleportationTarget";
  82224. this._isDefaultTeleportationTarget = false;
  82225. this._teleportationTarget = value;
  82226. }
  82227. },
  82228. enumerable: true,
  82229. configurable: true
  82230. });
  82231. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  82232. /**
  82233. * The mesh used to display where the user is selecting,
  82234. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  82235. * See http://doc.babylonjs.com/resources/baking_transformations
  82236. */
  82237. get: function () {
  82238. return this._cameraGazer._gazeTracker;
  82239. },
  82240. set: function (value) {
  82241. if (value) {
  82242. this._cameraGazer._gazeTracker = value;
  82243. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  82244. this._cameraGazer._gazeTracker.isPickable = false;
  82245. this._cameraGazer._gazeTracker.isVisible = false;
  82246. this._cameraGazer._gazeTracker.name = "gazeTracker";
  82247. if (this.leftController) {
  82248. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  82249. }
  82250. if (this.rightController) {
  82251. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  82252. }
  82253. }
  82254. },
  82255. enumerable: true,
  82256. configurable: true
  82257. });
  82258. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  82259. /**
  82260. * If the ray of the gaze should be displayed.
  82261. */
  82262. get: function () {
  82263. return this._displayGaze;
  82264. },
  82265. /**
  82266. * Sets if the ray of the gaze should be displayed.
  82267. */
  82268. set: function (value) {
  82269. this._displayGaze = value;
  82270. if (!value) {
  82271. this._cameraGazer._gazeTracker.isVisible = false;
  82272. if (this.leftController) {
  82273. this.leftController._gazeTracker.isVisible = false;
  82274. }
  82275. if (this.rightController) {
  82276. this.rightController._gazeTracker.isVisible = false;
  82277. }
  82278. }
  82279. },
  82280. enumerable: true,
  82281. configurable: true
  82282. });
  82283. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  82284. /**
  82285. * If the ray of the LaserPointer should be displayed.
  82286. */
  82287. get: function () {
  82288. return this._displayLaserPointer;
  82289. },
  82290. /**
  82291. * Sets if the ray of the LaserPointer should be displayed.
  82292. */
  82293. set: function (value) {
  82294. this._displayLaserPointer = value;
  82295. if (!value) {
  82296. if (this.rightController) {
  82297. this.rightController._deactivatePointer();
  82298. this.rightController._gazeTracker.isVisible = false;
  82299. }
  82300. if (this.leftController) {
  82301. this.leftController._deactivatePointer();
  82302. this.leftController._gazeTracker.isVisible = false;
  82303. }
  82304. }
  82305. else {
  82306. if (this.rightController) {
  82307. this.rightController._activatePointer();
  82308. }
  82309. else if (this.leftController) {
  82310. this.leftController._activatePointer();
  82311. }
  82312. }
  82313. },
  82314. enumerable: true,
  82315. configurable: true
  82316. });
  82317. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  82318. /**
  82319. * The deviceOrientationCamera used as the camera when not in VR.
  82320. */
  82321. get: function () {
  82322. return this._deviceOrientationCamera;
  82323. },
  82324. enumerable: true,
  82325. configurable: true
  82326. });
  82327. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  82328. /**
  82329. * Based on the current WebVR support, returns the current VR camera used.
  82330. */
  82331. get: function () {
  82332. if (this._webVRready) {
  82333. return this._webVRCamera;
  82334. }
  82335. else {
  82336. return this._scene.activeCamera;
  82337. }
  82338. },
  82339. enumerable: true,
  82340. configurable: true
  82341. });
  82342. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  82343. /**
  82344. * The webVRCamera which is used when in VR.
  82345. */
  82346. get: function () {
  82347. return this._webVRCamera;
  82348. },
  82349. enumerable: true,
  82350. configurable: true
  82351. });
  82352. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  82353. /**
  82354. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  82355. */
  82356. get: function () {
  82357. return this._vrDeviceOrientationCamera;
  82358. },
  82359. enumerable: true,
  82360. configurable: true
  82361. });
  82362. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  82363. get: function () {
  82364. var result = this._cameraGazer._teleportationRequestInitiated
  82365. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  82366. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  82367. return result;
  82368. },
  82369. enumerable: true,
  82370. configurable: true
  82371. });
  82372. // Raised when one of the controller has loaded successfully its associated default mesh
  82373. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  82374. if (this.leftController && this.leftController.webVRController == webVRController) {
  82375. if (webVRController.mesh) {
  82376. this.leftController._setLaserPointerParent(webVRController.mesh);
  82377. }
  82378. }
  82379. if (this.rightController && this.rightController.webVRController == webVRController) {
  82380. if (webVRController.mesh) {
  82381. this.rightController._setLaserPointerParent(webVRController.mesh);
  82382. }
  82383. }
  82384. try {
  82385. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  82386. }
  82387. catch (err) {
  82388. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  82389. }
  82390. };
  82391. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  82392. /**
  82393. * Gets a value indicating if we are currently in VR mode.
  82394. */
  82395. get: function () {
  82396. return this._webVRpresenting || this._fullscreenVRpresenting;
  82397. },
  82398. enumerable: true,
  82399. configurable: true
  82400. });
  82401. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  82402. var vrDisplay = this._scene.getEngine().getVRDevice();
  82403. if (vrDisplay) {
  82404. var wasPresenting = this._webVRpresenting;
  82405. // A VR display is connected
  82406. this._webVRpresenting = vrDisplay.isPresenting;
  82407. if (wasPresenting && !this._webVRpresenting)
  82408. this.exitVR();
  82409. }
  82410. else {
  82411. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  82412. }
  82413. this.updateButtonVisibility();
  82414. };
  82415. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  82416. this._webVRsupported = eventArgs.vrSupported;
  82417. this._webVRready = !!eventArgs.vrDisplay;
  82418. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  82419. this.updateButtonVisibility();
  82420. };
  82421. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  82422. if (this._canvas && !this._useCustomVRButton) {
  82423. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  82424. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  82425. }
  82426. };
  82427. VRExperienceHelper.prototype.displayVRButton = function () {
  82428. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  82429. document.body.appendChild(this._btnVR);
  82430. this._btnVRDisplayed = true;
  82431. }
  82432. };
  82433. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  82434. if (!this._btnVR || this._useCustomVRButton) {
  82435. return;
  82436. }
  82437. this._btnVR.className = "babylonVRicon";
  82438. if (this.isInVRMode) {
  82439. this._btnVR.className += " vrdisplaypresenting";
  82440. }
  82441. else {
  82442. if (this._webVRready)
  82443. this._btnVR.className += " vrdisplayready";
  82444. if (this._webVRsupported)
  82445. this._btnVR.className += " vrdisplaysupported";
  82446. if (this._webVRrequesting)
  82447. this._btnVR.className += " vrdisplayrequesting";
  82448. }
  82449. };
  82450. /**
  82451. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  82452. * Otherwise, will use the fullscreen API.
  82453. */
  82454. VRExperienceHelper.prototype.enterVR = function () {
  82455. if (this.onEnteringVRObservable) {
  82456. try {
  82457. this.onEnteringVRObservable.notifyObservers(this);
  82458. }
  82459. catch (err) {
  82460. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  82461. }
  82462. }
  82463. if (this._scene.activeCamera) {
  82464. this._position = this._scene.activeCamera.position.clone();
  82465. // make sure that we return to the last active camera
  82466. this._existingCamera = this._scene.activeCamera;
  82467. }
  82468. if (this._webVRrequesting)
  82469. return;
  82470. // If WebVR is supported and a headset is connected
  82471. if (this._webVRready) {
  82472. if (!this._webVRpresenting) {
  82473. this._webVRCamera.position = this._position;
  82474. this._scene.activeCamera = this._webVRCamera;
  82475. }
  82476. }
  82477. else if (this._vrDeviceOrientationCamera) {
  82478. this._vrDeviceOrientationCamera.position = this._position;
  82479. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  82480. this._scene.getEngine().switchFullscreen(true);
  82481. this.updateButtonVisibility();
  82482. }
  82483. if (this._scene.activeCamera && this._canvas) {
  82484. this._scene.activeCamera.attachControl(this._canvas);
  82485. }
  82486. if (this._interactionsEnabled) {
  82487. this._scene.registerBeforeRender(this.beforeRender);
  82488. }
  82489. };
  82490. /**
  82491. * Attempt to exit VR, or fullscreen.
  82492. */
  82493. VRExperienceHelper.prototype.exitVR = function () {
  82494. if (this.onExitingVRObservable) {
  82495. try {
  82496. this.onExitingVRObservable.notifyObservers(this);
  82497. }
  82498. catch (err) {
  82499. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  82500. }
  82501. }
  82502. if (this._webVRpresenting) {
  82503. this._scene.getEngine().disableVR();
  82504. }
  82505. if (this._scene.activeCamera) {
  82506. this._position = this._scene.activeCamera.position.clone();
  82507. }
  82508. if (this._deviceOrientationCamera) {
  82509. this._deviceOrientationCamera.position = this._position;
  82510. this._scene.activeCamera = this._deviceOrientationCamera;
  82511. if (this._canvas) {
  82512. this._scene.activeCamera.attachControl(this._canvas);
  82513. }
  82514. }
  82515. else if (this._existingCamera) {
  82516. this._existingCamera.position = this._position;
  82517. this._scene.activeCamera = this._existingCamera;
  82518. }
  82519. this.updateButtonVisibility();
  82520. if (this._interactionsEnabled) {
  82521. this._scene.unregisterBeforeRender(this.beforeRender);
  82522. }
  82523. };
  82524. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  82525. /**
  82526. * The position of the vr experience helper.
  82527. */
  82528. get: function () {
  82529. return this._position;
  82530. },
  82531. /**
  82532. * Sets the position of the vr experience helper.
  82533. */
  82534. set: function (value) {
  82535. this._position = value;
  82536. if (this._scene.activeCamera) {
  82537. this._scene.activeCamera.position = value;
  82538. }
  82539. },
  82540. enumerable: true,
  82541. configurable: true
  82542. });
  82543. /**
  82544. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  82545. */
  82546. VRExperienceHelper.prototype.enableInteractions = function () {
  82547. var _this = this;
  82548. if (!this._interactionsEnabled) {
  82549. this._interactionsRequested = true;
  82550. if (this.leftController) {
  82551. this._enableInteractionOnController(this.leftController);
  82552. }
  82553. if (this.rightController) {
  82554. this._enableInteractionOnController(this.rightController);
  82555. }
  82556. this.raySelectionPredicate = function (mesh) {
  82557. return mesh.isVisible;
  82558. };
  82559. this.meshSelectionPredicate = function (mesh) {
  82560. return true;
  82561. };
  82562. this._raySelectionPredicate = function (mesh) {
  82563. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  82564. && mesh.name.indexOf("teleportationTarget") === -1
  82565. && mesh.name.indexOf("torusTeleportation") === -1
  82566. && mesh.name.indexOf("laserPointer") === -1)) {
  82567. return _this.raySelectionPredicate(mesh);
  82568. }
  82569. return false;
  82570. };
  82571. this._interactionsEnabled = true;
  82572. }
  82573. };
  82574. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  82575. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  82576. if (this._floorMeshesCollection[i].id === mesh.id) {
  82577. return true;
  82578. }
  82579. }
  82580. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  82581. return true;
  82582. }
  82583. return false;
  82584. };
  82585. /**
  82586. * Adds a floor mesh to be used for teleportation.
  82587. * @param floorMesh the mesh to be used for teleportation.
  82588. */
  82589. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  82590. if (!this._floorMeshesCollection) {
  82591. return;
  82592. }
  82593. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  82594. return;
  82595. }
  82596. this._floorMeshesCollection.push(floorMesh);
  82597. };
  82598. /**
  82599. * Removes a floor mesh from being used for teleportation.
  82600. * @param floorMesh the mesh to be removed.
  82601. */
  82602. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  82603. if (!this._floorMeshesCollection) {
  82604. return;
  82605. }
  82606. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  82607. if (meshIndex !== -1) {
  82608. this._floorMeshesCollection.splice(meshIndex, 1);
  82609. }
  82610. };
  82611. /**
  82612. * Enables interactions and teleportation using the VR controllers and gaze.
  82613. * @param vrTeleportationOptions options to modify teleportation behavior.
  82614. */
  82615. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  82616. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  82617. if (!this._teleportationInitialized) {
  82618. this._teleportationRequested = true;
  82619. this.enableInteractions();
  82620. if (vrTeleportationOptions.floorMeshName) {
  82621. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  82622. }
  82623. if (vrTeleportationOptions.floorMeshes) {
  82624. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  82625. }
  82626. if (this.leftController != null) {
  82627. this._enableTeleportationOnController(this.leftController);
  82628. }
  82629. if (this.rightController != null) {
  82630. this._enableTeleportationOnController(this.rightController);
  82631. }
  82632. // Creates an image processing post process for the vignette not relying
  82633. // on the main scene configuration for image processing to reduce setup and spaces
  82634. // (gamma/linear) conflicts.
  82635. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  82636. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  82637. imageProcessingConfiguration.vignetteEnabled = true;
  82638. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  82639. this._webVRCamera.detachPostProcess(this._postProcessMove);
  82640. this._teleportationInitialized = true;
  82641. if (this._isDefaultTeleportationTarget) {
  82642. this._createTeleportationCircles();
  82643. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  82644. }
  82645. }
  82646. };
  82647. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  82648. var _this = this;
  82649. var controllerMesh = controller.webVRController.mesh;
  82650. if (controllerMesh) {
  82651. controller._interactionsEnabled = true;
  82652. controller._activatePointer();
  82653. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  82654. // Enabling / disabling laserPointer
  82655. if (_this._displayLaserPointer && stateObject.value === 1) {
  82656. if (controller._activePointer) {
  82657. controller._deactivatePointer();
  82658. }
  82659. else {
  82660. controller._activatePointer();
  82661. }
  82662. if (_this.displayGaze) {
  82663. controller._gazeTracker.isVisible = controller._activePointer;
  82664. }
  82665. }
  82666. });
  82667. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  82668. if (!controller._pointerDownOnMeshAsked) {
  82669. if (stateObject.value > _this._padSensibilityUp) {
  82670. controller._selectionPointerDown();
  82671. }
  82672. }
  82673. else if (stateObject.value < _this._padSensibilityDown) {
  82674. controller._selectionPointerUp();
  82675. }
  82676. });
  82677. }
  82678. };
  82679. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  82680. // Dont teleport if another gaze already requested teleportation
  82681. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  82682. return;
  82683. }
  82684. if (!gazer._teleportationRequestInitiated) {
  82685. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  82686. gazer._activatePointer();
  82687. gazer._teleportationRequestInitiated = true;
  82688. }
  82689. }
  82690. else {
  82691. // Listening to the proper controller values changes to confirm teleportation
  82692. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  82693. if (this._teleportActive) {
  82694. this._teleportCamera(this._haloCenter);
  82695. }
  82696. gazer._teleportationRequestInitiated = false;
  82697. }
  82698. }
  82699. };
  82700. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  82701. // Only rotate when user is not currently selecting a teleportation location
  82702. if (gazer._teleportationRequestInitiated) {
  82703. return;
  82704. }
  82705. if (!this._rotationLeftAsked) {
  82706. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  82707. this._rotationLeftAsked = true;
  82708. if (this._rotationAllowed) {
  82709. this._rotateCamera(false);
  82710. }
  82711. }
  82712. }
  82713. else {
  82714. if (stateObject.x > -this._padSensibilityDown) {
  82715. this._rotationLeftAsked = false;
  82716. }
  82717. }
  82718. if (!this._rotationRightAsked) {
  82719. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  82720. this._rotationRightAsked = true;
  82721. if (this._rotationAllowed) {
  82722. this._rotateCamera(true);
  82723. }
  82724. }
  82725. }
  82726. else {
  82727. if (stateObject.x < this._padSensibilityDown) {
  82728. this._rotationRightAsked = false;
  82729. }
  82730. }
  82731. };
  82732. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  82733. // Only teleport backwards when user is not currently selecting a teleportation location
  82734. if (gazer._teleportationRequestInitiated) {
  82735. return;
  82736. }
  82737. // Teleport backwards
  82738. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  82739. if (!gazer._teleportationBackRequestInitiated) {
  82740. if (!this.currentVRCamera) {
  82741. return;
  82742. }
  82743. // Get rotation and position of the current camera
  82744. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  82745. var position = this.currentVRCamera.position;
  82746. // If the camera has device position, use that instead
  82747. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  82748. rotation = this.currentVRCamera.deviceRotationQuaternion;
  82749. position = this.currentVRCamera.devicePosition;
  82750. }
  82751. // Get matrix with only the y rotation of the device rotation
  82752. rotation.toEulerAnglesToRef(this._workingVector);
  82753. this._workingVector.z = 0;
  82754. this._workingVector.x = 0;
  82755. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  82756. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  82757. // Rotate backwards ray by device rotation to cast at the ground behind the user
  82758. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  82759. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  82760. var ray = new BABYLON.Ray(position, this._workingVector);
  82761. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  82762. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  82763. this._teleportCamera(hit.pickedPoint);
  82764. }
  82765. gazer._teleportationBackRequestInitiated = true;
  82766. }
  82767. }
  82768. else {
  82769. gazer._teleportationBackRequestInitiated = false;
  82770. }
  82771. };
  82772. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  82773. var _this = this;
  82774. var controllerMesh = controller.webVRController.mesh;
  82775. if (controllerMesh) {
  82776. if (!controller._interactionsEnabled) {
  82777. this._enableInteractionOnController(controller);
  82778. }
  82779. controller._interactionsEnabled = true;
  82780. controller._teleportationEnabled = true;
  82781. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  82782. controller._dpadPressed = false;
  82783. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  82784. controller._dpadPressed = stateObject.pressed;
  82785. if (!controller._dpadPressed) {
  82786. _this._rotationLeftAsked = false;
  82787. _this._rotationRightAsked = false;
  82788. controller._teleportationBackRequestInitiated = false;
  82789. }
  82790. });
  82791. }
  82792. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  82793. if (_this.teleportationEnabled) {
  82794. _this._checkTeleportBackwards(stateObject, controller);
  82795. _this._checkTeleportWithRay(stateObject, controller);
  82796. }
  82797. _this._checkRotate(stateObject, controller);
  82798. });
  82799. }
  82800. };
  82801. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  82802. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  82803. this._teleportationTarget.isPickable = false;
  82804. var length = 512;
  82805. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  82806. dynamicTexture.hasAlpha = true;
  82807. var context = dynamicTexture.getContext();
  82808. var centerX = length / 2;
  82809. var centerY = length / 2;
  82810. var radius = 200;
  82811. context.beginPath();
  82812. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  82813. context.fillStyle = this._teleportationFillColor;
  82814. context.fill();
  82815. context.lineWidth = 10;
  82816. context.strokeStyle = this._teleportationBorderColor;
  82817. context.stroke();
  82818. context.closePath();
  82819. dynamicTexture.update();
  82820. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  82821. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  82822. this._teleportationTarget.material = teleportationCircleMaterial;
  82823. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  82824. torus.isPickable = false;
  82825. torus.parent = this._teleportationTarget;
  82826. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  82827. var keys = [];
  82828. keys.push({
  82829. frame: 0,
  82830. value: 0
  82831. });
  82832. keys.push({
  82833. frame: 30,
  82834. value: 0.4
  82835. });
  82836. keys.push({
  82837. frame: 60,
  82838. value: 0
  82839. });
  82840. animationInnerCircle.setKeys(keys);
  82841. var easingFunction = new BABYLON.SineEase();
  82842. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  82843. animationInnerCircle.setEasingFunction(easingFunction);
  82844. torus.animations = [];
  82845. torus.animations.push(animationInnerCircle);
  82846. this._scene.beginAnimation(torus, 0, 60, true);
  82847. this._hideTeleportationTarget();
  82848. };
  82849. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  82850. this._teleportActive = true;
  82851. if (this._teleportationInitialized) {
  82852. this._teleportationTarget.isVisible = true;
  82853. if (this._isDefaultTeleportationTarget) {
  82854. this._teleportationTarget.getChildren()[0].isVisible = true;
  82855. }
  82856. }
  82857. };
  82858. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  82859. this._teleportActive = false;
  82860. if (this._teleportationInitialized) {
  82861. this._teleportationTarget.isVisible = false;
  82862. if (this._isDefaultTeleportationTarget) {
  82863. this._teleportationTarget.getChildren()[0].isVisible = false;
  82864. }
  82865. }
  82866. };
  82867. VRExperienceHelper.prototype._rotateCamera = function (right) {
  82868. var _this = this;
  82869. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  82870. return;
  82871. }
  82872. if (right) {
  82873. this._rotationAngle++;
  82874. }
  82875. else {
  82876. this._rotationAngle--;
  82877. }
  82878. this.currentVRCamera.animations = [];
  82879. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  82880. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82881. var animationRotationKeys = [];
  82882. animationRotationKeys.push({
  82883. frame: 0,
  82884. value: this.currentVRCamera.rotationQuaternion
  82885. });
  82886. animationRotationKeys.push({
  82887. frame: 6,
  82888. value: target
  82889. });
  82890. animationRotation.setKeys(animationRotationKeys);
  82891. animationRotation.setEasingFunction(this._circleEase);
  82892. this.currentVRCamera.animations.push(animationRotation);
  82893. this._postProcessMove.animations = [];
  82894. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82895. var vignetteWeightKeys = [];
  82896. vignetteWeightKeys.push({
  82897. frame: 0,
  82898. value: 0
  82899. });
  82900. vignetteWeightKeys.push({
  82901. frame: 3,
  82902. value: 4
  82903. });
  82904. vignetteWeightKeys.push({
  82905. frame: 6,
  82906. value: 0
  82907. });
  82908. animationPP.setKeys(vignetteWeightKeys);
  82909. animationPP.setEasingFunction(this._circleEase);
  82910. this._postProcessMove.animations.push(animationPP);
  82911. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82912. var vignetteStretchKeys = [];
  82913. vignetteStretchKeys.push({
  82914. frame: 0,
  82915. value: 0
  82916. });
  82917. vignetteStretchKeys.push({
  82918. frame: 3,
  82919. value: 10
  82920. });
  82921. vignetteStretchKeys.push({
  82922. frame: 6,
  82923. value: 0
  82924. });
  82925. animationPP2.setKeys(vignetteStretchKeys);
  82926. animationPP2.setEasingFunction(this._circleEase);
  82927. this._postProcessMove.animations.push(animationPP2);
  82928. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  82929. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  82930. this._postProcessMove.samples = 4;
  82931. this._webVRCamera.attachPostProcess(this._postProcessMove);
  82932. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  82933. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  82934. });
  82935. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  82936. };
  82937. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  82938. if (hit.pickedPoint) {
  82939. if (gazer._teleportationRequestInitiated) {
  82940. this._displayTeleportationTarget();
  82941. this._haloCenter.copyFrom(hit.pickedPoint);
  82942. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  82943. }
  82944. var pickNormal = hit.getNormal(true, false);
  82945. if (pickNormal) {
  82946. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  82947. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  82948. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  82949. }
  82950. this._teleportationTarget.position.y += 0.1;
  82951. }
  82952. };
  82953. VRExperienceHelper.prototype._teleportCamera = function (location) {
  82954. var _this = this;
  82955. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  82956. return;
  82957. }
  82958. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  82959. // offset of the headset from the anchor.
  82960. if (this.webVRCamera.leftCamera) {
  82961. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  82962. this._workingVector.subtractInPlace(this.webVRCamera.position);
  82963. location.subtractToRef(this._workingVector, this._workingVector);
  82964. }
  82965. else {
  82966. this._workingVector.copyFrom(location);
  82967. }
  82968. // Add height to account for user's height offset
  82969. if (this.isInVRMode) {
  82970. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  82971. }
  82972. else {
  82973. this._workingVector.y += this._defaultHeight;
  82974. }
  82975. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  82976. // Create animation from the camera's position to the new location
  82977. this.currentVRCamera.animations = [];
  82978. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82979. var animationCameraTeleportationKeys = [{
  82980. frame: 0,
  82981. value: this.currentVRCamera.position
  82982. },
  82983. {
  82984. frame: 11,
  82985. value: this._workingVector
  82986. }
  82987. ];
  82988. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  82989. animationCameraTeleportation.setEasingFunction(this._circleEase);
  82990. this.currentVRCamera.animations.push(animationCameraTeleportation);
  82991. this._postProcessMove.animations = [];
  82992. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82993. var vignetteWeightKeys = [];
  82994. vignetteWeightKeys.push({
  82995. frame: 0,
  82996. value: 0
  82997. });
  82998. vignetteWeightKeys.push({
  82999. frame: 5,
  83000. value: 8
  83001. });
  83002. vignetteWeightKeys.push({
  83003. frame: 11,
  83004. value: 0
  83005. });
  83006. animationPP.setKeys(vignetteWeightKeys);
  83007. this._postProcessMove.animations.push(animationPP);
  83008. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83009. var vignetteStretchKeys = [];
  83010. vignetteStretchKeys.push({
  83011. frame: 0,
  83012. value: 0
  83013. });
  83014. vignetteStretchKeys.push({
  83015. frame: 5,
  83016. value: 10
  83017. });
  83018. vignetteStretchKeys.push({
  83019. frame: 11,
  83020. value: 0
  83021. });
  83022. animationPP2.setKeys(vignetteStretchKeys);
  83023. this._postProcessMove.animations.push(animationPP2);
  83024. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  83025. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  83026. this._webVRCamera.attachPostProcess(this._postProcessMove);
  83027. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  83028. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  83029. });
  83030. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  83031. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  83032. });
  83033. this._hideTeleportationTarget();
  83034. };
  83035. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  83036. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83037. return;
  83038. }
  83039. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  83040. // Moving the gazeTracker on the mesh face targetted
  83041. if (hit && hit.pickedPoint) {
  83042. if (this._displayGaze) {
  83043. var multiplier = 1;
  83044. gazer._gazeTracker.isVisible = true;
  83045. if (gazer._isActionableMesh) {
  83046. multiplier = 3;
  83047. }
  83048. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  83049. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  83050. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  83051. var pickNormal = hit.getNormal();
  83052. // To avoid z-fighting
  83053. var deltaFighting = 0.002;
  83054. if (pickNormal) {
  83055. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  83056. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  83057. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  83058. }
  83059. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  83060. if (gazer._gazeTracker.position.x < 0) {
  83061. gazer._gazeTracker.position.x += deltaFighting;
  83062. }
  83063. else {
  83064. gazer._gazeTracker.position.x -= deltaFighting;
  83065. }
  83066. if (gazer._gazeTracker.position.y < 0) {
  83067. gazer._gazeTracker.position.y += deltaFighting;
  83068. }
  83069. else {
  83070. gazer._gazeTracker.position.y -= deltaFighting;
  83071. }
  83072. if (gazer._gazeTracker.position.z < 0) {
  83073. gazer._gazeTracker.position.z += deltaFighting;
  83074. }
  83075. else {
  83076. gazer._gazeTracker.position.z -= deltaFighting;
  83077. }
  83078. }
  83079. // Changing the size of the laser pointer based on the distance from the targetted point
  83080. gazer._updatePointerDistance(hit.distance);
  83081. }
  83082. else {
  83083. gazer._gazeTracker.isVisible = false;
  83084. }
  83085. if (hit && hit.pickedMesh) {
  83086. gazer._currentHit = hit;
  83087. if (gazer._pointerDownOnMeshAsked) {
  83088. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  83089. }
  83090. // The object selected is the floor, we're in a teleportation scenario
  83091. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  83092. // Moving the teleportation area to this targetted point
  83093. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  83094. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  83095. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83096. }
  83097. gazer._currentMeshSelected = null;
  83098. if (gazer._teleportationRequestInitiated) {
  83099. this._moveTeleportationSelectorTo(hit, gazer);
  83100. }
  83101. return;
  83102. }
  83103. // If not, we're in a selection scenario
  83104. //this._teleportationAllowed = false;
  83105. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  83106. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  83107. this.onNewMeshPicked.notifyObservers(hit);
  83108. gazer._currentMeshSelected = hit.pickedMesh;
  83109. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  83110. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  83111. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  83112. gazer._isActionableMesh = true;
  83113. }
  83114. else {
  83115. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83116. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83117. gazer._isActionableMesh = false;
  83118. }
  83119. try {
  83120. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  83121. }
  83122. catch (err) {
  83123. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  83124. }
  83125. }
  83126. else {
  83127. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83128. gazer._currentMeshSelected = null;
  83129. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83130. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83131. }
  83132. }
  83133. }
  83134. else {
  83135. gazer._currentHit = null;
  83136. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83137. gazer._currentMeshSelected = null;
  83138. //this._teleportationAllowed = false;
  83139. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83140. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83141. }
  83142. };
  83143. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  83144. if (mesh) {
  83145. this.onSelectedMeshUnselected.notifyObservers(mesh);
  83146. }
  83147. };
  83148. /**
  83149. * Sets the color of the laser ray from the vr controllers.
  83150. * @param color new color for the ray.
  83151. */
  83152. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  83153. if (this.leftController) {
  83154. this.leftController._setLaserPointerColor(color);
  83155. }
  83156. if (this.rightController) {
  83157. this.rightController._setLaserPointerColor(color);
  83158. }
  83159. };
  83160. /**
  83161. * Sets the color of the ray from the vr headsets gaze.
  83162. * @param color new color for the ray.
  83163. */
  83164. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  83165. if (!this._cameraGazer._gazeTracker.material) {
  83166. return;
  83167. }
  83168. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  83169. if (this.leftController) {
  83170. this.leftController._gazeTracker.material.emissiveColor = color;
  83171. }
  83172. if (this.rightController) {
  83173. this.rightController._gazeTracker.material.emissiveColor = color;
  83174. }
  83175. };
  83176. /**
  83177. * Exits VR and disposes of the vr experience helper
  83178. */
  83179. VRExperienceHelper.prototype.dispose = function () {
  83180. if (this.isInVRMode) {
  83181. this.exitVR();
  83182. }
  83183. if (this._postProcessMove) {
  83184. this._postProcessMove.dispose();
  83185. }
  83186. if (this._webVRCamera) {
  83187. this._webVRCamera.dispose();
  83188. }
  83189. if (this._vrDeviceOrientationCamera) {
  83190. this._vrDeviceOrientationCamera.dispose();
  83191. }
  83192. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  83193. document.body.removeChild(this._btnVR);
  83194. }
  83195. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  83196. this._deviceOrientationCamera.dispose();
  83197. }
  83198. if (this._cameraGazer) {
  83199. this._cameraGazer.dispose();
  83200. }
  83201. if (this.leftController) {
  83202. this.leftController.dispose();
  83203. }
  83204. if (this.rightController) {
  83205. this.rightController.dispose();
  83206. }
  83207. if (this._teleportationTarget) {
  83208. this._teleportationTarget.dispose();
  83209. }
  83210. this._floorMeshesCollection = [];
  83211. document.removeEventListener("keydown", this._onKeyDown);
  83212. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  83213. window.removeEventListener("resize", this._onResize);
  83214. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  83215. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  83216. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  83217. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  83218. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  83219. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  83220. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  83221. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  83222. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  83223. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  83224. this._scene.unregisterBeforeRender(this.beforeRender);
  83225. };
  83226. /**
  83227. * Gets the name of the VRExperienceHelper class
  83228. * @returns "VRExperienceHelper"
  83229. */
  83230. VRExperienceHelper.prototype.getClassName = function () {
  83231. return "VRExperienceHelper";
  83232. };
  83233. return VRExperienceHelper;
  83234. }());
  83235. BABYLON.VRExperienceHelper = VRExperienceHelper;
  83236. })(BABYLON || (BABYLON = {}));
  83237. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  83238. "use strict";
  83239. // Mainly based on these 2 articles :
  83240. // 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
  83241. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  83242. var BABYLON;
  83243. (function (BABYLON) {
  83244. var JoystickAxis;
  83245. (function (JoystickAxis) {
  83246. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  83247. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  83248. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  83249. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  83250. var VirtualJoystick = /** @class */ (function () {
  83251. function VirtualJoystick(leftJoystick) {
  83252. var _this = this;
  83253. if (leftJoystick) {
  83254. this._leftJoystick = true;
  83255. }
  83256. else {
  83257. this._leftJoystick = false;
  83258. }
  83259. VirtualJoystick._globalJoystickIndex++;
  83260. // By default left & right arrow keys are moving the X
  83261. // and up & down keys are moving the Y
  83262. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  83263. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  83264. this.reverseLeftRight = false;
  83265. this.reverseUpDown = false;
  83266. // collections of pointers
  83267. this._touches = new BABYLON.StringDictionary();
  83268. this.deltaPosition = BABYLON.Vector3.Zero();
  83269. this._joystickSensibility = 25;
  83270. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  83271. this._onResize = function (evt) {
  83272. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  83273. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  83274. if (VirtualJoystick.vjCanvas) {
  83275. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  83276. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  83277. }
  83278. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  83279. };
  83280. // injecting a canvas element on top of the canvas 3D game
  83281. if (!VirtualJoystick.vjCanvas) {
  83282. window.addEventListener("resize", this._onResize, false);
  83283. VirtualJoystick.vjCanvas = document.createElement("canvas");
  83284. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  83285. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  83286. VirtualJoystick.vjCanvas.width = window.innerWidth;
  83287. VirtualJoystick.vjCanvas.height = window.innerHeight;
  83288. VirtualJoystick.vjCanvas.style.width = "100%";
  83289. VirtualJoystick.vjCanvas.style.height = "100%";
  83290. VirtualJoystick.vjCanvas.style.position = "absolute";
  83291. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  83292. VirtualJoystick.vjCanvas.style.top = "0px";
  83293. VirtualJoystick.vjCanvas.style.left = "0px";
  83294. VirtualJoystick.vjCanvas.style.zIndex = "5";
  83295. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  83296. // Support for jQuery PEP polyfill
  83297. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  83298. var context = VirtualJoystick.vjCanvas.getContext('2d');
  83299. if (!context) {
  83300. throw new Error("Unable to create canvas for virtual joystick");
  83301. }
  83302. VirtualJoystick.vjCanvasContext = context;
  83303. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  83304. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  83305. document.body.appendChild(VirtualJoystick.vjCanvas);
  83306. }
  83307. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  83308. this.pressed = false;
  83309. // default joystick color
  83310. this._joystickColor = "cyan";
  83311. this._joystickPointerID = -1;
  83312. // current joystick position
  83313. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  83314. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  83315. // origin joystick position
  83316. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  83317. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  83318. this._onPointerDownHandlerRef = function (evt) {
  83319. _this._onPointerDown(evt);
  83320. };
  83321. this._onPointerMoveHandlerRef = function (evt) {
  83322. _this._onPointerMove(evt);
  83323. };
  83324. this._onPointerUpHandlerRef = function (evt) {
  83325. _this._onPointerUp(evt);
  83326. };
  83327. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  83328. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  83329. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  83330. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  83331. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  83332. evt.preventDefault(); // Disables system menu
  83333. }, false);
  83334. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  83335. }
  83336. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  83337. this._joystickSensibility = newJoystickSensibility;
  83338. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  83339. };
  83340. VirtualJoystick.prototype._onPointerDown = function (e) {
  83341. var positionOnScreenCondition;
  83342. e.preventDefault();
  83343. if (this._leftJoystick === true) {
  83344. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  83345. }
  83346. else {
  83347. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  83348. }
  83349. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  83350. // First contact will be dedicated to the virtual joystick
  83351. this._joystickPointerID = e.pointerId;
  83352. this._joystickPointerStartPos.x = e.clientX;
  83353. this._joystickPointerStartPos.y = e.clientY;
  83354. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  83355. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  83356. this._deltaJoystickVector.x = 0;
  83357. this._deltaJoystickVector.y = 0;
  83358. this.pressed = true;
  83359. this._touches.add(e.pointerId.toString(), e);
  83360. }
  83361. else {
  83362. // You can only trigger the action buttons with a joystick declared
  83363. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  83364. this._action();
  83365. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  83366. }
  83367. }
  83368. };
  83369. VirtualJoystick.prototype._onPointerMove = function (e) {
  83370. // If the current pointer is the one associated to the joystick (first touch contact)
  83371. if (this._joystickPointerID == e.pointerId) {
  83372. this._joystickPointerPos.x = e.clientX;
  83373. this._joystickPointerPos.y = e.clientY;
  83374. this._deltaJoystickVector = this._joystickPointerPos.clone();
  83375. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  83376. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  83377. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  83378. switch (this._axisTargetedByLeftAndRight) {
  83379. case JoystickAxis.X:
  83380. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  83381. break;
  83382. case JoystickAxis.Y:
  83383. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  83384. break;
  83385. case JoystickAxis.Z:
  83386. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  83387. break;
  83388. }
  83389. var directionUpDown = this.reverseUpDown ? 1 : -1;
  83390. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  83391. switch (this._axisTargetedByUpAndDown) {
  83392. case JoystickAxis.X:
  83393. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  83394. break;
  83395. case JoystickAxis.Y:
  83396. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  83397. break;
  83398. case JoystickAxis.Z:
  83399. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  83400. break;
  83401. }
  83402. }
  83403. else {
  83404. var data = this._touches.get(e.pointerId.toString());
  83405. if (data) {
  83406. data.x = e.clientX;
  83407. data.y = e.clientY;
  83408. }
  83409. }
  83410. };
  83411. VirtualJoystick.prototype._onPointerUp = function (e) {
  83412. if (this._joystickPointerID == e.pointerId) {
  83413. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  83414. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  83415. this._joystickPointerID = -1;
  83416. this.pressed = false;
  83417. }
  83418. else {
  83419. var touch = this._touches.get(e.pointerId.toString());
  83420. if (touch) {
  83421. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  83422. }
  83423. }
  83424. this._deltaJoystickVector.x = 0;
  83425. this._deltaJoystickVector.y = 0;
  83426. this._touches.remove(e.pointerId.toString());
  83427. };
  83428. /**
  83429. * Change the color of the virtual joystick
  83430. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  83431. */
  83432. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  83433. this._joystickColor = newColor;
  83434. };
  83435. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  83436. this._action = action;
  83437. };
  83438. // Define which axis you'd like to control for left & right
  83439. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  83440. switch (axis) {
  83441. case JoystickAxis.X:
  83442. case JoystickAxis.Y:
  83443. case JoystickAxis.Z:
  83444. this._axisTargetedByLeftAndRight = axis;
  83445. break;
  83446. default:
  83447. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  83448. break;
  83449. }
  83450. };
  83451. // Define which axis you'd like to control for up & down
  83452. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  83453. switch (axis) {
  83454. case JoystickAxis.X:
  83455. case JoystickAxis.Y:
  83456. case JoystickAxis.Z:
  83457. this._axisTargetedByUpAndDown = axis;
  83458. break;
  83459. default:
  83460. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  83461. break;
  83462. }
  83463. };
  83464. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  83465. var _this = this;
  83466. if (this.pressed) {
  83467. this._touches.forEach(function (key, touch) {
  83468. if (touch.pointerId === _this._joystickPointerID) {
  83469. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  83470. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  83471. VirtualJoystick.vjCanvasContext.beginPath();
  83472. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  83473. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  83474. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  83475. VirtualJoystick.vjCanvasContext.stroke();
  83476. VirtualJoystick.vjCanvasContext.closePath();
  83477. VirtualJoystick.vjCanvasContext.beginPath();
  83478. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  83479. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  83480. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  83481. VirtualJoystick.vjCanvasContext.stroke();
  83482. VirtualJoystick.vjCanvasContext.closePath();
  83483. VirtualJoystick.vjCanvasContext.beginPath();
  83484. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  83485. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  83486. VirtualJoystick.vjCanvasContext.stroke();
  83487. VirtualJoystick.vjCanvasContext.closePath();
  83488. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  83489. }
  83490. else {
  83491. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  83492. VirtualJoystick.vjCanvasContext.beginPath();
  83493. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  83494. VirtualJoystick.vjCanvasContext.beginPath();
  83495. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  83496. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  83497. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  83498. VirtualJoystick.vjCanvasContext.stroke();
  83499. VirtualJoystick.vjCanvasContext.closePath();
  83500. touch.prevX = touch.x;
  83501. touch.prevY = touch.y;
  83502. }
  83503. ;
  83504. });
  83505. }
  83506. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  83507. };
  83508. VirtualJoystick.prototype.releaseCanvas = function () {
  83509. if (VirtualJoystick.vjCanvas) {
  83510. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  83511. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  83512. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  83513. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  83514. window.removeEventListener("resize", this._onResize);
  83515. document.body.removeChild(VirtualJoystick.vjCanvas);
  83516. VirtualJoystick.vjCanvas = null;
  83517. }
  83518. };
  83519. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  83520. VirtualJoystick._globalJoystickIndex = 0;
  83521. return VirtualJoystick;
  83522. }());
  83523. BABYLON.VirtualJoystick = VirtualJoystick;
  83524. })(BABYLON || (BABYLON = {}));
  83525. //# sourceMappingURL=babylon.virtualJoystick.js.map
  83526. "use strict";
  83527. var BABYLON;
  83528. (function (BABYLON) {
  83529. // We're mainly based on the logic defined into the FreeCamera code
  83530. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  83531. __extends(VirtualJoysticksCamera, _super);
  83532. function VirtualJoysticksCamera(name, position, scene) {
  83533. var _this = _super.call(this, name, position, scene) || this;
  83534. _this.inputs.addVirtualJoystick();
  83535. return _this;
  83536. }
  83537. VirtualJoysticksCamera.prototype.getClassName = function () {
  83538. return "VirtualJoysticksCamera";
  83539. };
  83540. return VirtualJoysticksCamera;
  83541. }(BABYLON.FreeCamera));
  83542. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  83543. })(BABYLON || (BABYLON = {}));
  83544. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  83545. "use strict";
  83546. var BABYLON;
  83547. (function (BABYLON) {
  83548. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  83549. function FreeCameraVirtualJoystickInput() {
  83550. }
  83551. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  83552. return this._leftjoystick;
  83553. };
  83554. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  83555. return this._rightjoystick;
  83556. };
  83557. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  83558. if (this._leftjoystick) {
  83559. var camera = this.camera;
  83560. var speed = camera._computeLocalCameraSpeed() * 50;
  83561. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  83562. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  83563. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  83564. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  83565. if (!this._leftjoystick.pressed) {
  83566. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  83567. }
  83568. if (!this._rightjoystick.pressed) {
  83569. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  83570. }
  83571. }
  83572. };
  83573. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  83574. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  83575. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  83576. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  83577. this._leftjoystick.setJoystickSensibility(0.15);
  83578. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  83579. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  83580. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  83581. this._rightjoystick.reverseUpDown = true;
  83582. this._rightjoystick.setJoystickSensibility(0.05);
  83583. this._rightjoystick.setJoystickColor("yellow");
  83584. };
  83585. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  83586. this._leftjoystick.releaseCanvas();
  83587. this._rightjoystick.releaseCanvas();
  83588. };
  83589. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  83590. return "FreeCameraVirtualJoystickInput";
  83591. };
  83592. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  83593. return "virtualJoystick";
  83594. };
  83595. return FreeCameraVirtualJoystickInput;
  83596. }());
  83597. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  83598. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  83599. })(BABYLON || (BABYLON = {}));
  83600. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  83601. "use strict";
  83602. var BABYLON;
  83603. (function (BABYLON) {
  83604. var SimplificationSettings = /** @class */ (function () {
  83605. function SimplificationSettings(quality, distance, optimizeMesh) {
  83606. this.quality = quality;
  83607. this.distance = distance;
  83608. this.optimizeMesh = optimizeMesh;
  83609. }
  83610. return SimplificationSettings;
  83611. }());
  83612. BABYLON.SimplificationSettings = SimplificationSettings;
  83613. var SimplificationQueue = /** @class */ (function () {
  83614. function SimplificationQueue() {
  83615. this.running = false;
  83616. this._simplificationArray = [];
  83617. }
  83618. SimplificationQueue.prototype.addTask = function (task) {
  83619. this._simplificationArray.push(task);
  83620. };
  83621. SimplificationQueue.prototype.executeNext = function () {
  83622. var task = this._simplificationArray.pop();
  83623. if (task) {
  83624. this.running = true;
  83625. this.runSimplification(task);
  83626. }
  83627. else {
  83628. this.running = false;
  83629. }
  83630. };
  83631. SimplificationQueue.prototype.runSimplification = function (task) {
  83632. var _this = this;
  83633. if (task.parallelProcessing) {
  83634. //parallel simplifier
  83635. task.settings.forEach(function (setting) {
  83636. var simplifier = _this.getSimplifier(task);
  83637. simplifier.simplify(setting, function (newMesh) {
  83638. task.mesh.addLODLevel(setting.distance, newMesh);
  83639. newMesh.isVisible = true;
  83640. //check if it is the last
  83641. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  83642. //all done, run the success callback.
  83643. task.successCallback();
  83644. }
  83645. _this.executeNext();
  83646. });
  83647. });
  83648. }
  83649. else {
  83650. //single simplifier.
  83651. var simplifier = this.getSimplifier(task);
  83652. var runDecimation = function (setting, callback) {
  83653. simplifier.simplify(setting, function (newMesh) {
  83654. task.mesh.addLODLevel(setting.distance, newMesh);
  83655. newMesh.isVisible = true;
  83656. //run the next quality level
  83657. callback();
  83658. });
  83659. };
  83660. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  83661. runDecimation(task.settings[loop.index], function () {
  83662. loop.executeNext();
  83663. });
  83664. }, function () {
  83665. //execution ended, run the success callback.
  83666. if (task.successCallback) {
  83667. task.successCallback();
  83668. }
  83669. _this.executeNext();
  83670. });
  83671. }
  83672. };
  83673. SimplificationQueue.prototype.getSimplifier = function (task) {
  83674. switch (task.simplificationType) {
  83675. case SimplificationType.QUADRATIC:
  83676. default:
  83677. return new QuadraticErrorSimplification(task.mesh);
  83678. }
  83679. };
  83680. return SimplificationQueue;
  83681. }());
  83682. BABYLON.SimplificationQueue = SimplificationQueue;
  83683. /**
  83684. * The implemented types of simplification.
  83685. * At the moment only Quadratic Error Decimation is implemented.
  83686. */
  83687. var SimplificationType;
  83688. (function (SimplificationType) {
  83689. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  83690. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  83691. var DecimationTriangle = /** @class */ (function () {
  83692. function DecimationTriangle(vertices) {
  83693. this.vertices = vertices;
  83694. this.error = new Array(4);
  83695. this.deleted = false;
  83696. this.isDirty = false;
  83697. this.deletePending = false;
  83698. this.borderFactor = 0;
  83699. }
  83700. return DecimationTriangle;
  83701. }());
  83702. BABYLON.DecimationTriangle = DecimationTriangle;
  83703. var DecimationVertex = /** @class */ (function () {
  83704. function DecimationVertex(position, id) {
  83705. this.position = position;
  83706. this.id = id;
  83707. this.isBorder = true;
  83708. this.q = new QuadraticMatrix();
  83709. this.triangleCount = 0;
  83710. this.triangleStart = 0;
  83711. this.originalOffsets = [];
  83712. }
  83713. DecimationVertex.prototype.updatePosition = function (newPosition) {
  83714. this.position.copyFrom(newPosition);
  83715. };
  83716. return DecimationVertex;
  83717. }());
  83718. BABYLON.DecimationVertex = DecimationVertex;
  83719. var QuadraticMatrix = /** @class */ (function () {
  83720. function QuadraticMatrix(data) {
  83721. this.data = new Array(10);
  83722. for (var i = 0; i < 10; ++i) {
  83723. if (data && data[i]) {
  83724. this.data[i] = data[i];
  83725. }
  83726. else {
  83727. this.data[i] = 0;
  83728. }
  83729. }
  83730. }
  83731. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  83732. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  83733. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  83734. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  83735. return det;
  83736. };
  83737. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  83738. for (var i = 0; i < 10; ++i) {
  83739. this.data[i] += matrix.data[i];
  83740. }
  83741. };
  83742. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  83743. for (var i = 0; i < 10; ++i) {
  83744. this.data[i] += data[i];
  83745. }
  83746. };
  83747. QuadraticMatrix.prototype.add = function (matrix) {
  83748. var m = new QuadraticMatrix();
  83749. for (var i = 0; i < 10; ++i) {
  83750. m.data[i] = this.data[i] + matrix.data[i];
  83751. }
  83752. return m;
  83753. };
  83754. QuadraticMatrix.FromData = function (a, b, c, d) {
  83755. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  83756. };
  83757. //returning an array to avoid garbage collection
  83758. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  83759. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  83760. };
  83761. return QuadraticMatrix;
  83762. }());
  83763. BABYLON.QuadraticMatrix = QuadraticMatrix;
  83764. var Reference = /** @class */ (function () {
  83765. function Reference(vertexId, triangleId) {
  83766. this.vertexId = vertexId;
  83767. this.triangleId = triangleId;
  83768. }
  83769. return Reference;
  83770. }());
  83771. BABYLON.Reference = Reference;
  83772. /**
  83773. * An implementation of the Quadratic Error simplification algorithm.
  83774. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  83775. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  83776. * @author RaananW
  83777. */
  83778. var QuadraticErrorSimplification = /** @class */ (function () {
  83779. function QuadraticErrorSimplification(_mesh) {
  83780. this._mesh = _mesh;
  83781. this.syncIterations = 5000;
  83782. this.aggressiveness = 7;
  83783. this.decimationIterations = 100;
  83784. this.boundingBoxEpsilon = BABYLON.Epsilon;
  83785. }
  83786. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  83787. var _this = this;
  83788. this.initDecimatedMesh();
  83789. //iterating through the submeshes array, one after the other.
  83790. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  83791. _this.initWithMesh(loop.index, function () {
  83792. _this.runDecimation(settings, loop.index, function () {
  83793. loop.executeNext();
  83794. });
  83795. }, settings.optimizeMesh);
  83796. }, function () {
  83797. setTimeout(function () {
  83798. successCallback(_this._reconstructedMesh);
  83799. }, 0);
  83800. });
  83801. };
  83802. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  83803. var _this = this;
  83804. var targetCount = ~~(this.triangles.length * settings.quality);
  83805. var deletedTriangles = 0;
  83806. var triangleCount = this.triangles.length;
  83807. var iterationFunction = function (iteration, callback) {
  83808. setTimeout(function () {
  83809. if (iteration % 5 === 0) {
  83810. _this.updateMesh(iteration === 0);
  83811. }
  83812. for (var i = 0; i < _this.triangles.length; ++i) {
  83813. _this.triangles[i].isDirty = false;
  83814. }
  83815. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  83816. var trianglesIterator = function (i) {
  83817. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  83818. var t = _this.triangles[tIdx];
  83819. if (!t)
  83820. return;
  83821. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  83822. return;
  83823. }
  83824. for (var j = 0; j < 3; ++j) {
  83825. if (t.error[j] < threshold) {
  83826. var deleted0 = [];
  83827. var deleted1 = [];
  83828. var v0 = t.vertices[j];
  83829. var v1 = t.vertices[(j + 1) % 3];
  83830. if (v0.isBorder || v1.isBorder)
  83831. continue;
  83832. var p = BABYLON.Vector3.Zero();
  83833. var n = BABYLON.Vector3.Zero();
  83834. var uv = BABYLON.Vector2.Zero();
  83835. var color = new BABYLON.Color4(0, 0, 0, 1);
  83836. _this.calculateError(v0, v1, p, n, uv, color);
  83837. var delTr = new Array();
  83838. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  83839. continue;
  83840. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  83841. continue;
  83842. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  83843. continue;
  83844. var uniqueArray = new Array();
  83845. delTr.forEach(function (deletedT) {
  83846. if (uniqueArray.indexOf(deletedT) === -1) {
  83847. deletedT.deletePending = true;
  83848. uniqueArray.push(deletedT);
  83849. }
  83850. });
  83851. if (uniqueArray.length % 2 !== 0) {
  83852. continue;
  83853. }
  83854. v0.q = v1.q.add(v0.q);
  83855. v0.updatePosition(p);
  83856. var tStart = _this.references.length;
  83857. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  83858. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  83859. var tCount = _this.references.length - tStart;
  83860. if (tCount <= v0.triangleCount) {
  83861. if (tCount) {
  83862. for (var c = 0; c < tCount; c++) {
  83863. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  83864. }
  83865. }
  83866. }
  83867. else {
  83868. v0.triangleStart = tStart;
  83869. }
  83870. v0.triangleCount = tCount;
  83871. break;
  83872. }
  83873. }
  83874. };
  83875. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  83876. }, 0);
  83877. };
  83878. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  83879. if (triangleCount - deletedTriangles <= targetCount)
  83880. loop.breakLoop();
  83881. else {
  83882. iterationFunction(loop.index, function () {
  83883. loop.executeNext();
  83884. });
  83885. }
  83886. }, function () {
  83887. setTimeout(function () {
  83888. //reconstruct this part of the mesh
  83889. _this.reconstructMesh(submeshIndex);
  83890. successCallback();
  83891. }, 0);
  83892. });
  83893. };
  83894. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  83895. var _this = this;
  83896. this.vertices = [];
  83897. this.triangles = [];
  83898. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  83899. var indices = this._mesh.getIndices();
  83900. var submesh = this._mesh.subMeshes[submeshIndex];
  83901. var findInVertices = function (positionToSearch) {
  83902. if (optimizeMesh) {
  83903. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  83904. if (_this.vertices[ii].position.equals(positionToSearch)) {
  83905. return _this.vertices[ii];
  83906. }
  83907. }
  83908. }
  83909. return null;
  83910. };
  83911. var vertexReferences = [];
  83912. var vertexInit = function (i) {
  83913. if (!positionData) {
  83914. return;
  83915. }
  83916. var offset = i + submesh.verticesStart;
  83917. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  83918. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  83919. vertex.originalOffsets.push(offset);
  83920. if (vertex.id === _this.vertices.length) {
  83921. _this.vertices.push(vertex);
  83922. }
  83923. vertexReferences.push(vertex.id);
  83924. };
  83925. //var totalVertices = mesh.getTotalVertices();
  83926. var totalVertices = submesh.verticesCount;
  83927. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  83928. var indicesInit = function (i) {
  83929. if (!indices) {
  83930. return;
  83931. }
  83932. var offset = (submesh.indexStart / 3) + i;
  83933. var pos = (offset * 3);
  83934. var i0 = indices[pos + 0];
  83935. var i1 = indices[pos + 1];
  83936. var i2 = indices[pos + 2];
  83937. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  83938. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  83939. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  83940. var triangle = new DecimationTriangle([v0, v1, v2]);
  83941. triangle.originalOffset = pos;
  83942. _this.triangles.push(triangle);
  83943. };
  83944. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  83945. _this.init(callback);
  83946. });
  83947. });
  83948. };
  83949. QuadraticErrorSimplification.prototype.init = function (callback) {
  83950. var _this = this;
  83951. var triangleInit1 = function (i) {
  83952. var t = _this.triangles[i];
  83953. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  83954. for (var j = 0; j < 3; j++) {
  83955. 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))));
  83956. }
  83957. };
  83958. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  83959. var triangleInit2 = function (i) {
  83960. var t = _this.triangles[i];
  83961. for (var j = 0; j < 3; ++j) {
  83962. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  83963. }
  83964. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  83965. };
  83966. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  83967. callback();
  83968. });
  83969. });
  83970. };
  83971. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  83972. var newTriangles = [];
  83973. var i;
  83974. for (i = 0; i < this.vertices.length; ++i) {
  83975. this.vertices[i].triangleCount = 0;
  83976. }
  83977. var t;
  83978. var j;
  83979. for (i = 0; i < this.triangles.length; ++i) {
  83980. if (!this.triangles[i].deleted) {
  83981. t = this.triangles[i];
  83982. for (j = 0; j < 3; ++j) {
  83983. t.vertices[j].triangleCount = 1;
  83984. }
  83985. newTriangles.push(t);
  83986. }
  83987. }
  83988. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  83989. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  83990. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  83991. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  83992. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  83993. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  83994. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  83995. var vertexCount = 0;
  83996. for (i = 0; i < this.vertices.length; ++i) {
  83997. var vertex = this.vertices[i];
  83998. vertex.id = vertexCount;
  83999. if (vertex.triangleCount) {
  84000. vertex.originalOffsets.forEach(function (originalOffset) {
  84001. if (!normalData) {
  84002. return;
  84003. }
  84004. newPositionData.push(vertex.position.x);
  84005. newPositionData.push(vertex.position.y);
  84006. newPositionData.push(vertex.position.z);
  84007. newNormalData.push(normalData[originalOffset * 3]);
  84008. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  84009. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  84010. if (uvs && uvs.length) {
  84011. newUVsData.push(uvs[(originalOffset * 2)]);
  84012. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  84013. }
  84014. else if (colorsData && colorsData.length) {
  84015. newColorsData.push(colorsData[(originalOffset * 4)]);
  84016. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  84017. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  84018. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  84019. }
  84020. ++vertexCount;
  84021. });
  84022. }
  84023. }
  84024. var startingIndex = this._reconstructedMesh.getTotalIndices();
  84025. var startingVertex = this._reconstructedMesh.getTotalVertices();
  84026. var submeshesArray = this._reconstructedMesh.subMeshes;
  84027. this._reconstructedMesh.subMeshes = [];
  84028. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  84029. var originalIndices = this._mesh.getIndices();
  84030. for (i = 0; i < newTriangles.length; ++i) {
  84031. t = newTriangles[i]; //now get the new referencing point for each vertex
  84032. [0, 1, 2].forEach(function (idx) {
  84033. var id = originalIndices[t.originalOffset + idx];
  84034. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  84035. if (offset < 0)
  84036. offset = 0;
  84037. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  84038. });
  84039. }
  84040. //overwriting the old vertex buffers and indices.
  84041. this._reconstructedMesh.setIndices(newIndicesArray);
  84042. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  84043. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  84044. if (newUVsData.length > 0)
  84045. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  84046. if (newColorsData.length > 0)
  84047. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  84048. //create submesh
  84049. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  84050. if (submeshIndex > 0) {
  84051. this._reconstructedMesh.subMeshes = [];
  84052. submeshesArray.forEach(function (submesh) {
  84053. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  84054. });
  84055. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  84056. }
  84057. };
  84058. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  84059. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  84060. this._reconstructedMesh.material = this._mesh.material;
  84061. this._reconstructedMesh.parent = this._mesh.parent;
  84062. this._reconstructedMesh.isVisible = false;
  84063. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  84064. };
  84065. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  84066. for (var i = 0; i < vertex1.triangleCount; ++i) {
  84067. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  84068. if (t.deleted)
  84069. continue;
  84070. var s = this.references[vertex1.triangleStart + i].vertexId;
  84071. var v1 = t.vertices[(s + 1) % 3];
  84072. var v2 = t.vertices[(s + 2) % 3];
  84073. if ((v1 === vertex2 || v2 === vertex2)) {
  84074. deletedArray[i] = true;
  84075. delTr.push(t);
  84076. continue;
  84077. }
  84078. var d1 = v1.position.subtract(point);
  84079. d1 = d1.normalize();
  84080. var d2 = v2.position.subtract(point);
  84081. d2 = d2.normalize();
  84082. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  84083. return true;
  84084. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  84085. deletedArray[i] = false;
  84086. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  84087. return true;
  84088. }
  84089. return false;
  84090. };
  84091. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  84092. var newDeleted = deletedTriangles;
  84093. for (var i = 0; i < vertex.triangleCount; ++i) {
  84094. var ref = this.references[vertex.triangleStart + i];
  84095. var t = this.triangles[ref.triangleId];
  84096. if (t.deleted)
  84097. continue;
  84098. if (deletedArray[i] && t.deletePending) {
  84099. t.deleted = true;
  84100. newDeleted++;
  84101. continue;
  84102. }
  84103. t.vertices[ref.vertexId] = origVertex;
  84104. t.isDirty = true;
  84105. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  84106. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  84107. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  84108. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  84109. this.references.push(ref);
  84110. }
  84111. return newDeleted;
  84112. };
  84113. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  84114. for (var i = 0; i < this.vertices.length; ++i) {
  84115. var vCount = [];
  84116. var vId = [];
  84117. var v = this.vertices[i];
  84118. var j;
  84119. for (j = 0; j < v.triangleCount; ++j) {
  84120. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  84121. for (var ii = 0; ii < 3; ii++) {
  84122. var ofs = 0;
  84123. var vv = triangle.vertices[ii];
  84124. while (ofs < vCount.length) {
  84125. if (vId[ofs] === vv.id)
  84126. break;
  84127. ++ofs;
  84128. }
  84129. if (ofs === vCount.length) {
  84130. vCount.push(1);
  84131. vId.push(vv.id);
  84132. }
  84133. else {
  84134. vCount[ofs]++;
  84135. }
  84136. }
  84137. }
  84138. for (j = 0; j < vCount.length; ++j) {
  84139. if (vCount[j] === 1) {
  84140. this.vertices[vId[j]].isBorder = true;
  84141. }
  84142. else {
  84143. this.vertices[vId[j]].isBorder = false;
  84144. }
  84145. }
  84146. }
  84147. };
  84148. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  84149. if (identifyBorders === void 0) { identifyBorders = false; }
  84150. var i;
  84151. if (!identifyBorders) {
  84152. var newTrianglesVector = [];
  84153. for (i = 0; i < this.triangles.length; ++i) {
  84154. if (!this.triangles[i].deleted) {
  84155. newTrianglesVector.push(this.triangles[i]);
  84156. }
  84157. }
  84158. this.triangles = newTrianglesVector;
  84159. }
  84160. for (i = 0; i < this.vertices.length; ++i) {
  84161. this.vertices[i].triangleCount = 0;
  84162. this.vertices[i].triangleStart = 0;
  84163. }
  84164. var t;
  84165. var j;
  84166. var v;
  84167. for (i = 0; i < this.triangles.length; ++i) {
  84168. t = this.triangles[i];
  84169. for (j = 0; j < 3; ++j) {
  84170. v = t.vertices[j];
  84171. v.triangleCount++;
  84172. }
  84173. }
  84174. var tStart = 0;
  84175. for (i = 0; i < this.vertices.length; ++i) {
  84176. this.vertices[i].triangleStart = tStart;
  84177. tStart += this.vertices[i].triangleCount;
  84178. this.vertices[i].triangleCount = 0;
  84179. }
  84180. var newReferences = new Array(this.triangles.length * 3);
  84181. for (i = 0; i < this.triangles.length; ++i) {
  84182. t = this.triangles[i];
  84183. for (j = 0; j < 3; ++j) {
  84184. v = t.vertices[j];
  84185. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  84186. v.triangleCount++;
  84187. }
  84188. }
  84189. this.references = newReferences;
  84190. if (identifyBorders) {
  84191. this.identifyBorder();
  84192. }
  84193. };
  84194. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  84195. var x = point.x;
  84196. var y = point.y;
  84197. var z = point.z;
  84198. 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
  84199. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  84200. };
  84201. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  84202. var q = vertex1.q.add(vertex2.q);
  84203. var border = vertex1.isBorder && vertex2.isBorder;
  84204. var error = 0;
  84205. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  84206. if (qDet !== 0 && !border) {
  84207. if (!pointResult) {
  84208. pointResult = BABYLON.Vector3.Zero();
  84209. }
  84210. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  84211. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  84212. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  84213. error = this.vertexError(q, pointResult);
  84214. }
  84215. else {
  84216. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  84217. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  84218. var error1 = this.vertexError(q, vertex1.position);
  84219. var error2 = this.vertexError(q, vertex2.position);
  84220. var error3 = this.vertexError(q, p3);
  84221. error = Math.min(error1, error2, error3);
  84222. if (error === error1) {
  84223. if (pointResult) {
  84224. pointResult.copyFrom(vertex1.position);
  84225. }
  84226. }
  84227. else if (error === error2) {
  84228. if (pointResult) {
  84229. pointResult.copyFrom(vertex2.position);
  84230. }
  84231. }
  84232. else {
  84233. if (pointResult) {
  84234. pointResult.copyFrom(p3);
  84235. }
  84236. }
  84237. }
  84238. return error;
  84239. };
  84240. return QuadraticErrorSimplification;
  84241. }());
  84242. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  84243. })(BABYLON || (BABYLON = {}));
  84244. //# sourceMappingURL=babylon.meshSimplification.js.map
  84245. "use strict";
  84246. var BABYLON;
  84247. (function (BABYLON) {
  84248. var MeshLODLevel = /** @class */ (function () {
  84249. function MeshLODLevel(distance, mesh) {
  84250. this.distance = distance;
  84251. this.mesh = mesh;
  84252. }
  84253. return MeshLODLevel;
  84254. }());
  84255. BABYLON.MeshLODLevel = MeshLODLevel;
  84256. })(BABYLON || (BABYLON = {}));
  84257. //# sourceMappingURL=babylon.meshLODLevel.js.map
  84258. "use strict";
  84259. var BABYLON;
  84260. (function (BABYLON) {
  84261. /**
  84262. * Defines the root class used to create scene optimization to use with SceneOptimizer
  84263. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84264. */
  84265. var SceneOptimization = /** @class */ (function () {
  84266. /**
  84267. * Creates the SceneOptimization object
  84268. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84269. * @param desc defines the description associated with the optimization
  84270. */
  84271. function SceneOptimization(
  84272. /**
  84273. * Defines the priority of this optimization (0 by default which means first in the list)
  84274. */
  84275. priority) {
  84276. if (priority === void 0) { priority = 0; }
  84277. this.priority = priority;
  84278. }
  84279. /**
  84280. * Gets a string describing the action executed by the current optimization
  84281. * @returns description string
  84282. */
  84283. SceneOptimization.prototype.getDescription = function () {
  84284. return "";
  84285. };
  84286. /**
  84287. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84288. * @param scene defines the current scene where to apply this optimization
  84289. * @param optimizer defines the current optimizer
  84290. * @returns true if everything that can be done was applied
  84291. */
  84292. SceneOptimization.prototype.apply = function (scene, optimizer) {
  84293. return true;
  84294. };
  84295. ;
  84296. return SceneOptimization;
  84297. }());
  84298. BABYLON.SceneOptimization = SceneOptimization;
  84299. /**
  84300. * Defines an optimization used to reduce the size of render target textures
  84301. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84302. */
  84303. var TextureOptimization = /** @class */ (function (_super) {
  84304. __extends(TextureOptimization, _super);
  84305. /**
  84306. * Creates the TextureOptimization object
  84307. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84308. * @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
  84309. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  84310. */
  84311. function TextureOptimization(
  84312. /**
  84313. * Defines the priority of this optimization (0 by default which means first in the list)
  84314. */
  84315. priority,
  84316. /**
  84317. * 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
  84318. */
  84319. maximumSize,
  84320. /**
  84321. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  84322. */
  84323. step) {
  84324. if (priority === void 0) { priority = 0; }
  84325. if (maximumSize === void 0) { maximumSize = 1024; }
  84326. if (step === void 0) { step = 0.5; }
  84327. var _this = _super.call(this, priority) || this;
  84328. _this.priority = priority;
  84329. _this.maximumSize = maximumSize;
  84330. _this.step = step;
  84331. return _this;
  84332. }
  84333. /**
  84334. * Gets a string describing the action executed by the current optimization
  84335. * @returns description string
  84336. */
  84337. TextureOptimization.prototype.getDescription = function () {
  84338. return "Reducing render target texture size to " + this.maximumSize;
  84339. };
  84340. /**
  84341. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84342. * @param scene defines the current scene where to apply this optimization
  84343. * @param optimizer defines the current optimizer
  84344. * @returns true if everything that can be done was applied
  84345. */
  84346. TextureOptimization.prototype.apply = function (scene, optimizer) {
  84347. var allDone = true;
  84348. for (var index = 0; index < scene.textures.length; index++) {
  84349. var texture = scene.textures[index];
  84350. if (!texture.canRescale || texture.getContext) {
  84351. continue;
  84352. }
  84353. var currentSize = texture.getSize();
  84354. var maxDimension = Math.max(currentSize.width, currentSize.height);
  84355. if (maxDimension > this.maximumSize) {
  84356. texture.scale(this.step);
  84357. allDone = false;
  84358. }
  84359. }
  84360. return allDone;
  84361. };
  84362. return TextureOptimization;
  84363. }(SceneOptimization));
  84364. BABYLON.TextureOptimization = TextureOptimization;
  84365. /**
  84366. * Defines an optimization used to increase or decrease the rendering resolution
  84367. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84368. */
  84369. var HardwareScalingOptimization = /** @class */ (function (_super) {
  84370. __extends(HardwareScalingOptimization, _super);
  84371. /**
  84372. * Creates the HardwareScalingOptimization object
  84373. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84374. * @param maximumScale defines the maximum scale to use (2 by default)
  84375. * @param step defines the step to use between two passes (0.5 by default)
  84376. */
  84377. function HardwareScalingOptimization(
  84378. /**
  84379. * Defines the priority of this optimization (0 by default which means first in the list)
  84380. */
  84381. priority,
  84382. /**
  84383. * Defines the maximum scale to use (2 by default)
  84384. */
  84385. maximumScale,
  84386. /**
  84387. * Defines the step to use between two passes (0.5 by default)
  84388. */
  84389. step) {
  84390. if (priority === void 0) { priority = 0; }
  84391. if (maximumScale === void 0) { maximumScale = 2; }
  84392. if (step === void 0) { step = 0.25; }
  84393. var _this = _super.call(this, priority) || this;
  84394. _this.priority = priority;
  84395. _this.maximumScale = maximumScale;
  84396. _this.step = step;
  84397. _this._currentScale = -1;
  84398. _this._directionOffset = 1;
  84399. return _this;
  84400. }
  84401. /**
  84402. * Gets a string describing the action executed by the current optimization
  84403. * @return description string
  84404. */
  84405. HardwareScalingOptimization.prototype.getDescription = function () {
  84406. return "Setting hardware scaling level to " + this._currentScale;
  84407. };
  84408. /**
  84409. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84410. * @param scene defines the current scene where to apply this optimization
  84411. * @param optimizer defines the current optimizer
  84412. * @returns true if everything that can be done was applied
  84413. */
  84414. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  84415. if (this._currentScale === -1) {
  84416. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  84417. if (this._currentScale > this.maximumScale) {
  84418. this._directionOffset = -1;
  84419. }
  84420. }
  84421. this._currentScale += this._directionOffset * this.step;
  84422. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  84423. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  84424. };
  84425. ;
  84426. return HardwareScalingOptimization;
  84427. }(SceneOptimization));
  84428. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  84429. /**
  84430. * Defines an optimization used to remove shadows
  84431. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84432. */
  84433. var ShadowsOptimization = /** @class */ (function (_super) {
  84434. __extends(ShadowsOptimization, _super);
  84435. function ShadowsOptimization() {
  84436. return _super !== null && _super.apply(this, arguments) || this;
  84437. }
  84438. /**
  84439. * Gets a string describing the action executed by the current optimization
  84440. * @return description string
  84441. */
  84442. ShadowsOptimization.prototype.getDescription = function () {
  84443. return "Turning shadows on/off";
  84444. };
  84445. /**
  84446. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84447. * @param scene defines the current scene where to apply this optimization
  84448. * @param optimizer defines the current optimizer
  84449. * @returns true if everything that can be done was applied
  84450. */
  84451. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  84452. scene.shadowsEnabled = optimizer.isInImprovementMode;
  84453. return true;
  84454. };
  84455. ;
  84456. return ShadowsOptimization;
  84457. }(SceneOptimization));
  84458. BABYLON.ShadowsOptimization = ShadowsOptimization;
  84459. /**
  84460. * Defines an optimization used to turn post-processes off
  84461. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84462. */
  84463. var PostProcessesOptimization = /** @class */ (function (_super) {
  84464. __extends(PostProcessesOptimization, _super);
  84465. function PostProcessesOptimization() {
  84466. return _super !== null && _super.apply(this, arguments) || this;
  84467. }
  84468. /**
  84469. * Gets a string describing the action executed by the current optimization
  84470. * @return description string
  84471. */
  84472. PostProcessesOptimization.prototype.getDescription = function () {
  84473. return "Turning post-processes on/off";
  84474. };
  84475. /**
  84476. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84477. * @param scene defines the current scene where to apply this optimization
  84478. * @param optimizer defines the current optimizer
  84479. * @returns true if everything that can be done was applied
  84480. */
  84481. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  84482. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  84483. return true;
  84484. };
  84485. ;
  84486. return PostProcessesOptimization;
  84487. }(SceneOptimization));
  84488. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  84489. /**
  84490. * Defines an optimization used to turn lens flares off
  84491. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84492. */
  84493. var LensFlaresOptimization = /** @class */ (function (_super) {
  84494. __extends(LensFlaresOptimization, _super);
  84495. function LensFlaresOptimization() {
  84496. return _super !== null && _super.apply(this, arguments) || this;
  84497. }
  84498. /**
  84499. * Gets a string describing the action executed by the current optimization
  84500. * @return description string
  84501. */
  84502. LensFlaresOptimization.prototype.getDescription = function () {
  84503. return "Turning lens flares on/off";
  84504. };
  84505. /**
  84506. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84507. * @param scene defines the current scene where to apply this optimization
  84508. * @param optimizer defines the current optimizer
  84509. * @returns true if everything that can be done was applied
  84510. */
  84511. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  84512. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  84513. return true;
  84514. };
  84515. ;
  84516. return LensFlaresOptimization;
  84517. }(SceneOptimization));
  84518. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  84519. /**
  84520. * Defines an optimization based on user defined callback.
  84521. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84522. */
  84523. var CustomOptimization = /** @class */ (function (_super) {
  84524. __extends(CustomOptimization, _super);
  84525. function CustomOptimization() {
  84526. return _super !== null && _super.apply(this, arguments) || this;
  84527. }
  84528. /**
  84529. * Gets a string describing the action executed by the current optimization
  84530. * @returns description string
  84531. */
  84532. CustomOptimization.prototype.getDescription = function () {
  84533. if (this.onGetDescription) {
  84534. return this.onGetDescription();
  84535. }
  84536. return "Running user defined callback";
  84537. };
  84538. /**
  84539. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84540. * @param scene defines the current scene where to apply this optimization
  84541. * @param optimizer defines the current optimizer
  84542. * @returns true if everything that can be done was applied
  84543. */
  84544. CustomOptimization.prototype.apply = function (scene, optimizer) {
  84545. if (this.onApply) {
  84546. return this.onApply(scene, optimizer);
  84547. }
  84548. return true;
  84549. };
  84550. ;
  84551. return CustomOptimization;
  84552. }(SceneOptimization));
  84553. BABYLON.CustomOptimization = CustomOptimization;
  84554. /**
  84555. * Defines an optimization used to turn particles off
  84556. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84557. */
  84558. var ParticlesOptimization = /** @class */ (function (_super) {
  84559. __extends(ParticlesOptimization, _super);
  84560. function ParticlesOptimization() {
  84561. return _super !== null && _super.apply(this, arguments) || this;
  84562. }
  84563. /**
  84564. * Gets a string describing the action executed by the current optimization
  84565. * @return description string
  84566. */
  84567. ParticlesOptimization.prototype.getDescription = function () {
  84568. return "Turning particles on/off";
  84569. };
  84570. /**
  84571. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84572. * @param scene defines the current scene where to apply this optimization
  84573. * @param optimizer defines the current optimizer
  84574. * @returns true if everything that can be done was applied
  84575. */
  84576. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  84577. scene.particlesEnabled = optimizer.isInImprovementMode;
  84578. return true;
  84579. };
  84580. ;
  84581. return ParticlesOptimization;
  84582. }(SceneOptimization));
  84583. BABYLON.ParticlesOptimization = ParticlesOptimization;
  84584. /**
  84585. * Defines an optimization used to turn render targets off
  84586. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84587. */
  84588. var RenderTargetsOptimization = /** @class */ (function (_super) {
  84589. __extends(RenderTargetsOptimization, _super);
  84590. function RenderTargetsOptimization() {
  84591. return _super !== null && _super.apply(this, arguments) || this;
  84592. }
  84593. /**
  84594. * Gets a string describing the action executed by the current optimization
  84595. * @return description string
  84596. */
  84597. RenderTargetsOptimization.prototype.getDescription = function () {
  84598. return "Turning render targets off";
  84599. };
  84600. /**
  84601. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84602. * @param scene defines the current scene where to apply this optimization
  84603. * @param optimizer defines the current optimizer
  84604. * @returns true if everything that can be done was applied
  84605. */
  84606. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  84607. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  84608. return true;
  84609. };
  84610. ;
  84611. return RenderTargetsOptimization;
  84612. }(SceneOptimization));
  84613. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  84614. /**
  84615. * Defines an optimization used to merge meshes with compatible materials
  84616. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84617. */
  84618. var MergeMeshesOptimization = /** @class */ (function (_super) {
  84619. __extends(MergeMeshesOptimization, _super);
  84620. function MergeMeshesOptimization() {
  84621. var _this = _super !== null && _super.apply(this, arguments) || this;
  84622. _this._canBeMerged = function (abstractMesh) {
  84623. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  84624. return false;
  84625. }
  84626. var mesh = abstractMesh;
  84627. if (!mesh.isVisible || !mesh.isEnabled()) {
  84628. return false;
  84629. }
  84630. if (mesh.instances.length > 0) {
  84631. return false;
  84632. }
  84633. if (mesh.skeleton || mesh.hasLODLevels) {
  84634. return false;
  84635. }
  84636. if (mesh.parent) {
  84637. return false;
  84638. }
  84639. return true;
  84640. };
  84641. return _this;
  84642. }
  84643. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  84644. /**
  84645. * Gets or sets a boolean which defines if optimization octree has to be updated
  84646. */
  84647. get: function () {
  84648. return MergeMeshesOptimization._UpdateSelectionTree;
  84649. },
  84650. /**
  84651. * Gets or sets a boolean which defines if optimization octree has to be updated
  84652. */
  84653. set: function (value) {
  84654. MergeMeshesOptimization._UpdateSelectionTree = value;
  84655. },
  84656. enumerable: true,
  84657. configurable: true
  84658. });
  84659. /**
  84660. * Gets a string describing the action executed by the current optimization
  84661. * @return description string
  84662. */
  84663. MergeMeshesOptimization.prototype.getDescription = function () {
  84664. return "Merging similar meshes together";
  84665. };
  84666. /**
  84667. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84668. * @param scene defines the current scene where to apply this optimization
  84669. * @param optimizer defines the current optimizer
  84670. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  84671. * @returns true if everything that can be done was applied
  84672. */
  84673. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  84674. var globalPool = scene.meshes.slice(0);
  84675. var globalLength = globalPool.length;
  84676. for (var index = 0; index < globalLength; index++) {
  84677. var currentPool = new Array();
  84678. var current = globalPool[index];
  84679. // Checks
  84680. if (!this._canBeMerged(current)) {
  84681. continue;
  84682. }
  84683. currentPool.push(current);
  84684. // Find compatible meshes
  84685. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  84686. var otherMesh = globalPool[subIndex];
  84687. if (!this._canBeMerged(otherMesh)) {
  84688. continue;
  84689. }
  84690. if (otherMesh.material !== current.material) {
  84691. continue;
  84692. }
  84693. if (otherMesh.checkCollisions !== current.checkCollisions) {
  84694. continue;
  84695. }
  84696. currentPool.push(otherMesh);
  84697. globalLength--;
  84698. globalPool.splice(subIndex, 1);
  84699. subIndex--;
  84700. }
  84701. if (currentPool.length < 2) {
  84702. continue;
  84703. }
  84704. // Merge meshes
  84705. BABYLON.Mesh.MergeMeshes(currentPool);
  84706. }
  84707. if (updateSelectionTree != undefined) {
  84708. if (updateSelectionTree) {
  84709. scene.createOrUpdateSelectionOctree();
  84710. }
  84711. }
  84712. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  84713. scene.createOrUpdateSelectionOctree();
  84714. }
  84715. return true;
  84716. };
  84717. ;
  84718. MergeMeshesOptimization._UpdateSelectionTree = false;
  84719. return MergeMeshesOptimization;
  84720. }(SceneOptimization));
  84721. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  84722. /**
  84723. * Defines a list of options used by SceneOptimizer
  84724. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84725. */
  84726. var SceneOptimizerOptions = /** @class */ (function () {
  84727. /**
  84728. * Creates a new list of options used by SceneOptimizer
  84729. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  84730. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  84731. */
  84732. function SceneOptimizerOptions(
  84733. /**
  84734. * Defines the target frame rate to reach (60 by default)
  84735. */
  84736. targetFrameRate,
  84737. /**
  84738. * Defines the interval between two checkes (2000ms by default)
  84739. */
  84740. trackerDuration) {
  84741. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  84742. if (trackerDuration === void 0) { trackerDuration = 2000; }
  84743. this.targetFrameRate = targetFrameRate;
  84744. this.trackerDuration = trackerDuration;
  84745. /**
  84746. * Gets the list of optimizations to apply
  84747. */
  84748. this.optimizations = new Array();
  84749. }
  84750. /**
  84751. * Add a new optimization
  84752. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  84753. * @returns the current SceneOptimizerOptions
  84754. */
  84755. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  84756. this.optimizations.push(optimization);
  84757. return this;
  84758. };
  84759. /**
  84760. * Add a new custom optimization
  84761. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  84762. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  84763. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84764. * @returns the current SceneOptimizerOptions
  84765. */
  84766. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  84767. if (priority === void 0) { priority = 0; }
  84768. var optimization = new CustomOptimization(priority);
  84769. optimization.onApply = onApply;
  84770. optimization.onGetDescription = onGetDescription;
  84771. this.optimizations.push(optimization);
  84772. return this;
  84773. };
  84774. /**
  84775. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  84776. * @param targetFrameRate defines the target frame rate (60 by default)
  84777. * @returns a SceneOptimizerOptions object
  84778. */
  84779. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  84780. var result = new SceneOptimizerOptions(targetFrameRate);
  84781. var priority = 0;
  84782. result.addOptimization(new MergeMeshesOptimization(priority));
  84783. result.addOptimization(new ShadowsOptimization(priority));
  84784. result.addOptimization(new LensFlaresOptimization(priority));
  84785. // Next priority
  84786. priority++;
  84787. result.addOptimization(new PostProcessesOptimization(priority));
  84788. result.addOptimization(new ParticlesOptimization(priority));
  84789. // Next priority
  84790. priority++;
  84791. result.addOptimization(new TextureOptimization(priority, 1024));
  84792. return result;
  84793. };
  84794. /**
  84795. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  84796. * @param targetFrameRate defines the target frame rate (60 by default)
  84797. * @returns a SceneOptimizerOptions object
  84798. */
  84799. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  84800. var result = new SceneOptimizerOptions(targetFrameRate);
  84801. var priority = 0;
  84802. result.addOptimization(new MergeMeshesOptimization(priority));
  84803. result.addOptimization(new ShadowsOptimization(priority));
  84804. result.addOptimization(new LensFlaresOptimization(priority));
  84805. // Next priority
  84806. priority++;
  84807. result.addOptimization(new PostProcessesOptimization(priority));
  84808. result.addOptimization(new ParticlesOptimization(priority));
  84809. // Next priority
  84810. priority++;
  84811. result.addOptimization(new TextureOptimization(priority, 512));
  84812. // Next priority
  84813. priority++;
  84814. result.addOptimization(new RenderTargetsOptimization(priority));
  84815. // Next priority
  84816. priority++;
  84817. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  84818. return result;
  84819. };
  84820. /**
  84821. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  84822. * @param targetFrameRate defines the target frame rate (60 by default)
  84823. * @returns a SceneOptimizerOptions object
  84824. */
  84825. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  84826. var result = new SceneOptimizerOptions(targetFrameRate);
  84827. var priority = 0;
  84828. result.addOptimization(new MergeMeshesOptimization(priority));
  84829. result.addOptimization(new ShadowsOptimization(priority));
  84830. result.addOptimization(new LensFlaresOptimization(priority));
  84831. // Next priority
  84832. priority++;
  84833. result.addOptimization(new PostProcessesOptimization(priority));
  84834. result.addOptimization(new ParticlesOptimization(priority));
  84835. // Next priority
  84836. priority++;
  84837. result.addOptimization(new TextureOptimization(priority, 256));
  84838. // Next priority
  84839. priority++;
  84840. result.addOptimization(new RenderTargetsOptimization(priority));
  84841. // Next priority
  84842. priority++;
  84843. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  84844. return result;
  84845. };
  84846. return SceneOptimizerOptions;
  84847. }());
  84848. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  84849. /**
  84850. * Class used to run optimizations in order to reach a target frame rate
  84851. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84852. */
  84853. var SceneOptimizer = /** @class */ (function () {
  84854. /**
  84855. * Creates a new SceneOptimizer
  84856. * @param scene defines the scene to work on
  84857. * @param options defines the options to use with the SceneOptimizer
  84858. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  84859. * @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)
  84860. */
  84861. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  84862. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  84863. if (improvementMode === void 0) { improvementMode = false; }
  84864. var _this = this;
  84865. this._isRunning = false;
  84866. this._currentPriorityLevel = 0;
  84867. this._targetFrameRate = 60;
  84868. this._trackerDuration = 2000;
  84869. this._currentFrameRate = 0;
  84870. this._improvementMode = false;
  84871. /**
  84872. * Defines an observable called when the optimizer reaches the target frame rate
  84873. */
  84874. this.onSuccessObservable = new BABYLON.Observable();
  84875. /**
  84876. * Defines an observable called when the optimizer enables an optimization
  84877. */
  84878. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  84879. /**
  84880. * Defines an observable called when the optimizer is not able to reach the target frame rate
  84881. */
  84882. this.onFailureObservable = new BABYLON.Observable();
  84883. if (!options) {
  84884. this._options = new SceneOptimizerOptions();
  84885. }
  84886. else {
  84887. this._options = options;
  84888. }
  84889. if (this._options.targetFrameRate) {
  84890. this._targetFrameRate = this._options.targetFrameRate;
  84891. }
  84892. if (this._options.trackerDuration) {
  84893. this._trackerDuration = this._options.trackerDuration;
  84894. }
  84895. if (autoGeneratePriorities) {
  84896. var priority = 0;
  84897. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  84898. var optim = _a[_i];
  84899. optim.priority = priority++;
  84900. }
  84901. }
  84902. this._improvementMode = improvementMode;
  84903. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84904. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  84905. _this._sceneDisposeObserver = null;
  84906. _this.dispose();
  84907. });
  84908. }
  84909. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  84910. /**
  84911. * Gets a boolean indicating if the optimizer is in improvement mode
  84912. */
  84913. get: function () {
  84914. return this._improvementMode;
  84915. },
  84916. enumerable: true,
  84917. configurable: true
  84918. });
  84919. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  84920. /**
  84921. * Gets the current priority level (0 at start)
  84922. */
  84923. get: function () {
  84924. return this._currentPriorityLevel;
  84925. },
  84926. enumerable: true,
  84927. configurable: true
  84928. });
  84929. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  84930. /**
  84931. * Gets the current frame rate checked by the SceneOptimizer
  84932. */
  84933. get: function () {
  84934. return this._currentFrameRate;
  84935. },
  84936. enumerable: true,
  84937. configurable: true
  84938. });
  84939. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  84940. /**
  84941. * Gets or sets the current target frame rate (60 by default)
  84942. */
  84943. get: function () {
  84944. return this._targetFrameRate;
  84945. },
  84946. /**
  84947. * Gets or sets the current target frame rate (60 by default)
  84948. */
  84949. set: function (value) {
  84950. this._targetFrameRate = value;
  84951. },
  84952. enumerable: true,
  84953. configurable: true
  84954. });
  84955. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  84956. /**
  84957. * Gets or sets the current interval between two checks (every 2000ms by default)
  84958. */
  84959. get: function () {
  84960. return this._trackerDuration;
  84961. },
  84962. /**
  84963. * Gets or sets the current interval between two checks (every 2000ms by default)
  84964. */
  84965. set: function (value) {
  84966. this._trackerDuration = value;
  84967. },
  84968. enumerable: true,
  84969. configurable: true
  84970. });
  84971. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  84972. /**
  84973. * Gets the list of active optimizations
  84974. */
  84975. get: function () {
  84976. return this._options.optimizations;
  84977. },
  84978. enumerable: true,
  84979. configurable: true
  84980. });
  84981. /**
  84982. * Stops the current optimizer
  84983. */
  84984. SceneOptimizer.prototype.stop = function () {
  84985. this._isRunning = false;
  84986. };
  84987. /**
  84988. * Reset the optimizer to initial step (current priority level = 0)
  84989. */
  84990. SceneOptimizer.prototype.reset = function () {
  84991. this._currentPriorityLevel = 0;
  84992. };
  84993. /**
  84994. * Start the optimizer. By default it will try to reach a specific framerate
  84995. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  84996. */
  84997. SceneOptimizer.prototype.start = function () {
  84998. var _this = this;
  84999. if (this._isRunning) {
  85000. return;
  85001. }
  85002. this._isRunning = true;
  85003. // Let's wait for the scene to be ready before running our check
  85004. this._scene.executeWhenReady(function () {
  85005. setTimeout(function () {
  85006. _this._checkCurrentState();
  85007. }, _this._trackerDuration);
  85008. });
  85009. };
  85010. SceneOptimizer.prototype._checkCurrentState = function () {
  85011. var _this = this;
  85012. if (!this._isRunning) {
  85013. return;
  85014. }
  85015. var scene = this._scene;
  85016. var options = this._options;
  85017. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  85018. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  85019. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  85020. this._isRunning = false;
  85021. this.onSuccessObservable.notifyObservers(this);
  85022. return;
  85023. }
  85024. // Apply current level of optimizations
  85025. var allDone = true;
  85026. var noOptimizationApplied = true;
  85027. for (var index = 0; index < options.optimizations.length; index++) {
  85028. var optimization = options.optimizations[index];
  85029. if (optimization.priority === this._currentPriorityLevel) {
  85030. noOptimizationApplied = false;
  85031. allDone = allDone && optimization.apply(scene, this);
  85032. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  85033. }
  85034. }
  85035. // If no optimization was applied, this is a failure :(
  85036. if (noOptimizationApplied) {
  85037. this._isRunning = false;
  85038. this.onFailureObservable.notifyObservers(this);
  85039. return;
  85040. }
  85041. // If all optimizations were done, move to next level
  85042. if (allDone) {
  85043. this._currentPriorityLevel++;
  85044. }
  85045. // Let's the system running for a specific amount of time before checking FPS
  85046. scene.executeWhenReady(function () {
  85047. setTimeout(function () {
  85048. _this._checkCurrentState();
  85049. }, _this._trackerDuration);
  85050. });
  85051. };
  85052. /**
  85053. * Release all resources
  85054. */
  85055. SceneOptimizer.prototype.dispose = function () {
  85056. this.stop();
  85057. this.onSuccessObservable.clear();
  85058. this.onFailureObservable.clear();
  85059. this.onNewOptimizationAppliedObservable.clear();
  85060. if (this._sceneDisposeObserver) {
  85061. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  85062. }
  85063. };
  85064. /**
  85065. * Helper function to create a SceneOptimizer with one single line of code
  85066. * @param scene defines the scene to work on
  85067. * @param options defines the options to use with the SceneOptimizer
  85068. * @param onSuccess defines a callback to call on success
  85069. * @param onFailure defines a callback to call on failure
  85070. * @returns the new SceneOptimizer object
  85071. */
  85072. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  85073. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  85074. if (onSuccess) {
  85075. optimizer.onSuccessObservable.add(function () {
  85076. onSuccess();
  85077. });
  85078. }
  85079. if (onFailure) {
  85080. optimizer.onFailureObservable.add(function () {
  85081. onFailure();
  85082. });
  85083. }
  85084. optimizer.start();
  85085. return optimizer;
  85086. };
  85087. return SceneOptimizer;
  85088. }());
  85089. BABYLON.SceneOptimizer = SceneOptimizer;
  85090. })(BABYLON || (BABYLON = {}));
  85091. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  85092. "use strict";
  85093. var BABYLON;
  85094. (function (BABYLON) {
  85095. var OutlineRenderer = /** @class */ (function () {
  85096. function OutlineRenderer(scene) {
  85097. this.zOffset = 1;
  85098. this._scene = scene;
  85099. }
  85100. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  85101. var _this = this;
  85102. if (useOverlay === void 0) { useOverlay = false; }
  85103. var scene = this._scene;
  85104. var engine = this._scene.getEngine();
  85105. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  85106. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  85107. return;
  85108. }
  85109. var mesh = subMesh.getRenderingMesh();
  85110. var material = subMesh.getMaterial();
  85111. if (!material || !scene.activeCamera) {
  85112. return;
  85113. }
  85114. engine.enableEffect(this._effect);
  85115. // Logarithmic depth
  85116. if (material.useLogarithmicDepth) {
  85117. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  85118. }
  85119. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  85120. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  85121. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  85122. // Bones
  85123. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  85124. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  85125. }
  85126. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  85127. // Alpha test
  85128. if (material && material.needAlphaTesting()) {
  85129. var alphaTexture = material.getAlphaTestTexture();
  85130. if (alphaTexture) {
  85131. this._effect.setTexture("diffuseSampler", alphaTexture);
  85132. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  85133. }
  85134. }
  85135. engine.setZOffset(-this.zOffset);
  85136. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  85137. engine.setZOffset(0);
  85138. };
  85139. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  85140. var defines = [];
  85141. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  85142. var mesh = subMesh.getMesh();
  85143. var material = subMesh.getMaterial();
  85144. if (material) {
  85145. // Alpha test
  85146. if (material.needAlphaTesting()) {
  85147. defines.push("#define ALPHATEST");
  85148. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85149. attribs.push(BABYLON.VertexBuffer.UVKind);
  85150. defines.push("#define UV1");
  85151. }
  85152. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  85153. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85154. defines.push("#define UV2");
  85155. }
  85156. }
  85157. //Logarithmic depth
  85158. if (material.useLogarithmicDepth) {
  85159. defines.push("#define LOGARITHMICDEPTH");
  85160. }
  85161. }
  85162. // Bones
  85163. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  85164. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  85165. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  85166. if (mesh.numBoneInfluencers > 4) {
  85167. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  85168. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  85169. }
  85170. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  85171. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  85172. }
  85173. else {
  85174. defines.push("#define NUM_BONE_INFLUENCERS 0");
  85175. }
  85176. // Instances
  85177. if (useInstances) {
  85178. defines.push("#define INSTANCES");
  85179. attribs.push("world0");
  85180. attribs.push("world1");
  85181. attribs.push("world2");
  85182. attribs.push("world3");
  85183. }
  85184. // Get correct effect
  85185. var join = defines.join("\n");
  85186. if (this._cachedDefines !== join) {
  85187. this._cachedDefines = join;
  85188. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  85189. }
  85190. return this._effect.isReady();
  85191. };
  85192. return OutlineRenderer;
  85193. }());
  85194. BABYLON.OutlineRenderer = OutlineRenderer;
  85195. })(BABYLON || (BABYLON = {}));
  85196. //# sourceMappingURL=babylon.outlineRenderer.js.map
  85197. "use strict";
  85198. var BABYLON;
  85199. (function (BABYLON) {
  85200. var FaceAdjacencies = /** @class */ (function () {
  85201. function FaceAdjacencies() {
  85202. this.edges = new Array();
  85203. this.edgesConnectedCount = 0;
  85204. }
  85205. return FaceAdjacencies;
  85206. }());
  85207. var EdgesRenderer = /** @class */ (function () {
  85208. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  85209. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  85210. if (epsilon === void 0) { epsilon = 0.95; }
  85211. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  85212. this.edgesWidthScalerForOrthographic = 1000.0;
  85213. this.edgesWidthScalerForPerspective = 50.0;
  85214. this._linesPositions = new Array();
  85215. this._linesNormals = new Array();
  85216. this._linesIndices = new Array();
  85217. this._buffers = {};
  85218. this._checkVerticesInsteadOfIndices = false;
  85219. this._source = source;
  85220. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  85221. this._epsilon = epsilon;
  85222. this._prepareRessources();
  85223. this._generateEdgesLines();
  85224. }
  85225. EdgesRenderer.prototype._prepareRessources = function () {
  85226. if (this._lineShader) {
  85227. return;
  85228. }
  85229. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  85230. attributes: ["position", "normal"],
  85231. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  85232. });
  85233. this._lineShader.disableDepthWrite = true;
  85234. this._lineShader.backFaceCulling = false;
  85235. };
  85236. EdgesRenderer.prototype._rebuild = function () {
  85237. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  85238. if (buffer) {
  85239. buffer._rebuild();
  85240. }
  85241. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  85242. if (buffer) {
  85243. buffer._rebuild();
  85244. }
  85245. var scene = this._source.getScene();
  85246. var engine = scene.getEngine();
  85247. this._ib = engine.createIndexBuffer(this._linesIndices);
  85248. };
  85249. EdgesRenderer.prototype.dispose = function () {
  85250. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  85251. if (buffer) {
  85252. buffer.dispose();
  85253. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  85254. }
  85255. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  85256. if (buffer) {
  85257. buffer.dispose();
  85258. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  85259. }
  85260. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  85261. this._lineShader.dispose();
  85262. };
  85263. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  85264. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  85265. return 0;
  85266. }
  85267. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  85268. return 1;
  85269. }
  85270. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  85271. return 2;
  85272. }
  85273. return -1;
  85274. };
  85275. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  85276. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  85277. return 0;
  85278. }
  85279. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  85280. return 1;
  85281. }
  85282. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  85283. return 2;
  85284. }
  85285. return -1;
  85286. };
  85287. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  85288. var needToCreateLine;
  85289. if (edge === undefined) {
  85290. needToCreateLine = true;
  85291. }
  85292. else {
  85293. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  85294. needToCreateLine = dotProduct < this._epsilon;
  85295. }
  85296. if (needToCreateLine) {
  85297. var offset = this._linesPositions.length / 3;
  85298. var normal = p0.subtract(p1);
  85299. normal.normalize();
  85300. // Positions
  85301. this._linesPositions.push(p0.x);
  85302. this._linesPositions.push(p0.y);
  85303. this._linesPositions.push(p0.z);
  85304. this._linesPositions.push(p0.x);
  85305. this._linesPositions.push(p0.y);
  85306. this._linesPositions.push(p0.z);
  85307. this._linesPositions.push(p1.x);
  85308. this._linesPositions.push(p1.y);
  85309. this._linesPositions.push(p1.z);
  85310. this._linesPositions.push(p1.x);
  85311. this._linesPositions.push(p1.y);
  85312. this._linesPositions.push(p1.z);
  85313. // Normals
  85314. this._linesNormals.push(p1.x);
  85315. this._linesNormals.push(p1.y);
  85316. this._linesNormals.push(p1.z);
  85317. this._linesNormals.push(-1);
  85318. this._linesNormals.push(p1.x);
  85319. this._linesNormals.push(p1.y);
  85320. this._linesNormals.push(p1.z);
  85321. this._linesNormals.push(1);
  85322. this._linesNormals.push(p0.x);
  85323. this._linesNormals.push(p0.y);
  85324. this._linesNormals.push(p0.z);
  85325. this._linesNormals.push(-1);
  85326. this._linesNormals.push(p0.x);
  85327. this._linesNormals.push(p0.y);
  85328. this._linesNormals.push(p0.z);
  85329. this._linesNormals.push(1);
  85330. // Indices
  85331. this._linesIndices.push(offset);
  85332. this._linesIndices.push(offset + 1);
  85333. this._linesIndices.push(offset + 2);
  85334. this._linesIndices.push(offset);
  85335. this._linesIndices.push(offset + 2);
  85336. this._linesIndices.push(offset + 3);
  85337. }
  85338. };
  85339. EdgesRenderer.prototype._generateEdgesLines = function () {
  85340. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  85341. var indices = this._source.getIndices();
  85342. if (!indices || !positions) {
  85343. return;
  85344. }
  85345. // First let's find adjacencies
  85346. var adjacencies = new Array();
  85347. var faceNormals = new Array();
  85348. var index;
  85349. var faceAdjacencies;
  85350. // Prepare faces
  85351. for (index = 0; index < indices.length; index += 3) {
  85352. faceAdjacencies = new FaceAdjacencies();
  85353. var p0Index = indices[index];
  85354. var p1Index = indices[index + 1];
  85355. var p2Index = indices[index + 2];
  85356. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  85357. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  85358. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  85359. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  85360. faceNormal.normalize();
  85361. faceNormals.push(faceNormal);
  85362. adjacencies.push(faceAdjacencies);
  85363. }
  85364. // Scan
  85365. for (index = 0; index < adjacencies.length; index++) {
  85366. faceAdjacencies = adjacencies[index];
  85367. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  85368. var otherFaceAdjacencies = adjacencies[otherIndex];
  85369. if (faceAdjacencies.edgesConnectedCount === 3) {
  85370. break;
  85371. }
  85372. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  85373. continue;
  85374. }
  85375. var otherP0 = indices[otherIndex * 3];
  85376. var otherP1 = indices[otherIndex * 3 + 1];
  85377. var otherP2 = indices[otherIndex * 3 + 2];
  85378. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  85379. var otherEdgeIndex = 0;
  85380. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  85381. continue;
  85382. }
  85383. switch (edgeIndex) {
  85384. case 0:
  85385. if (this._checkVerticesInsteadOfIndices) {
  85386. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  85387. }
  85388. else {
  85389. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  85390. }
  85391. break;
  85392. case 1:
  85393. if (this._checkVerticesInsteadOfIndices) {
  85394. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  85395. }
  85396. else {
  85397. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  85398. }
  85399. break;
  85400. case 2:
  85401. if (this._checkVerticesInsteadOfIndices) {
  85402. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  85403. }
  85404. else {
  85405. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  85406. }
  85407. break;
  85408. }
  85409. if (otherEdgeIndex === -1) {
  85410. continue;
  85411. }
  85412. faceAdjacencies.edges[edgeIndex] = otherIndex;
  85413. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  85414. faceAdjacencies.edgesConnectedCount++;
  85415. otherFaceAdjacencies.edgesConnectedCount++;
  85416. if (faceAdjacencies.edgesConnectedCount === 3) {
  85417. break;
  85418. }
  85419. }
  85420. }
  85421. }
  85422. // Create lines
  85423. for (index = 0; index < adjacencies.length; index++) {
  85424. // 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
  85425. var current = adjacencies[index];
  85426. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  85427. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  85428. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  85429. }
  85430. // Merge into a single mesh
  85431. var engine = this._source.getScene().getEngine();
  85432. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  85433. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  85434. this._ib = engine.createIndexBuffer(this._linesIndices);
  85435. this._indicesCount = this._linesIndices.length;
  85436. };
  85437. EdgesRenderer.prototype.render = function () {
  85438. var scene = this._source.getScene();
  85439. if (!this._lineShader.isReady() || !scene.activeCamera) {
  85440. return;
  85441. }
  85442. var engine = scene.getEngine();
  85443. this._lineShader._preBind();
  85444. // VBOs
  85445. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  85446. scene.resetCachedMaterial();
  85447. this._lineShader.setColor4("color", this._source.edgesColor);
  85448. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  85449. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  85450. }
  85451. else {
  85452. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  85453. }
  85454. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  85455. this._lineShader.bind(this._source.getWorldMatrix());
  85456. // Draw order
  85457. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  85458. this._lineShader.unbind();
  85459. engine.setDepthWrite(true);
  85460. };
  85461. return EdgesRenderer;
  85462. }());
  85463. BABYLON.EdgesRenderer = EdgesRenderer;
  85464. })(BABYLON || (BABYLON = {}));
  85465. //# sourceMappingURL=babylon.edgesRenderer.js.map
  85466. "use strict";
  85467. var __assign = (this && this.__assign) || Object.assign || function(t) {
  85468. for (var s, i = 1, n = arguments.length; i < n; i++) {
  85469. s = arguments[i];
  85470. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  85471. t[p] = s[p];
  85472. }
  85473. return t;
  85474. };
  85475. var BABYLON;
  85476. (function (BABYLON) {
  85477. /**
  85478. * The effect layer Helps adding post process effect blended with the main pass.
  85479. *
  85480. * This can be for instance use to generate glow or higlight effects on the scene.
  85481. *
  85482. * The effect layer class can not be used directly and is intented to inherited from to be
  85483. * customized per effects.
  85484. */
  85485. var EffectLayer = /** @class */ (function () {
  85486. /**
  85487. * Instantiates a new effect Layer and references it in the scene.
  85488. * @param name The name of the layer
  85489. * @param scene The scene to use the layer in
  85490. */
  85491. function EffectLayer(
  85492. /** The Friendly of the effect in the scene */
  85493. name, scene) {
  85494. this.name = name;
  85495. this._vertexBuffers = {};
  85496. this._maxSize = 0;
  85497. this._mainTextureDesiredSize = { width: 0, height: 0 };
  85498. this._shouldRender = true;
  85499. this._postProcesses = [];
  85500. this._textures = [];
  85501. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  85502. /**
  85503. * The clear color of the texture used to generate the glow map.
  85504. */
  85505. this.neutralColor = new BABYLON.Color4();
  85506. /**
  85507. * Specifies wether the highlight layer is enabled or not.
  85508. */
  85509. this.isEnabled = true;
  85510. /**
  85511. * An event triggered when the effect layer has been disposed.
  85512. */
  85513. this.onDisposeObservable = new BABYLON.Observable();
  85514. /**
  85515. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  85516. */
  85517. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  85518. /**
  85519. * An event triggered when the generated texture is being merged in the scene.
  85520. */
  85521. this.onBeforeComposeObservable = new BABYLON.Observable();
  85522. /**
  85523. * An event triggered when the generated texture has been merged in the scene.
  85524. */
  85525. this.onAfterComposeObservable = new BABYLON.Observable();
  85526. /**
  85527. * An event triggered when the efffect layer changes its size.
  85528. */
  85529. this.onSizeChangedObservable = new BABYLON.Observable();
  85530. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85531. this._engine = scene.getEngine();
  85532. this._maxSize = this._engine.getCaps().maxTextureSize;
  85533. this._scene.effectLayers.push(this);
  85534. // Generate Buffers
  85535. this._generateIndexBuffer();
  85536. this._genrateVertexBuffer();
  85537. }
  85538. Object.defineProperty(EffectLayer.prototype, "camera", {
  85539. /**
  85540. * Gets the camera attached to the layer.
  85541. */
  85542. get: function () {
  85543. return this._effectLayerOptions.camera;
  85544. },
  85545. enumerable: true,
  85546. configurable: true
  85547. });
  85548. /**
  85549. * Initializes the effect layer with the required options.
  85550. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  85551. */
  85552. EffectLayer.prototype._init = function (options) {
  85553. // Adapt options
  85554. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  85555. this._setMainTextureSize();
  85556. this._createMainTexture();
  85557. this._createTextureAndPostProcesses();
  85558. this._mergeEffect = this._createMergeEffect();
  85559. };
  85560. /**
  85561. * Generates the index buffer of the full screen quad blending to the main canvas.
  85562. */
  85563. EffectLayer.prototype._generateIndexBuffer = function () {
  85564. // Indices
  85565. var indices = [];
  85566. indices.push(0);
  85567. indices.push(1);
  85568. indices.push(2);
  85569. indices.push(0);
  85570. indices.push(2);
  85571. indices.push(3);
  85572. this._indexBuffer = this._engine.createIndexBuffer(indices);
  85573. };
  85574. /**
  85575. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  85576. */
  85577. EffectLayer.prototype._genrateVertexBuffer = function () {
  85578. // VBO
  85579. var vertices = [];
  85580. vertices.push(1, 1);
  85581. vertices.push(-1, 1);
  85582. vertices.push(-1, -1);
  85583. vertices.push(1, -1);
  85584. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  85585. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  85586. };
  85587. /**
  85588. * Sets the main texture desired size which is the closest power of two
  85589. * of the engine canvas size.
  85590. */
  85591. EffectLayer.prototype._setMainTextureSize = function () {
  85592. if (this._effectLayerOptions.mainTextureFixedSize) {
  85593. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  85594. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  85595. }
  85596. else {
  85597. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  85598. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  85599. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  85600. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  85601. }
  85602. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  85603. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  85604. };
  85605. /**
  85606. * Creates the main texture for the effect layer.
  85607. */
  85608. EffectLayer.prototype._createMainTexture = function () {
  85609. var _this = this;
  85610. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  85611. width: this._mainTextureDesiredSize.width,
  85612. height: this._mainTextureDesiredSize.height
  85613. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  85614. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  85615. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85616. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85617. this._mainTexture.anisotropicFilteringLevel = 1;
  85618. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85619. this._mainTexture.renderParticles = false;
  85620. this._mainTexture.renderList = null;
  85621. this._mainTexture.ignoreCameraViewport = true;
  85622. // Custom render function
  85623. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  85624. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  85625. var index;
  85626. var engine = _this._scene.getEngine();
  85627. if (depthOnlySubMeshes.length) {
  85628. engine.setColorWrite(false);
  85629. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  85630. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  85631. }
  85632. engine.setColorWrite(true);
  85633. }
  85634. for (index = 0; index < opaqueSubMeshes.length; index++) {
  85635. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  85636. }
  85637. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  85638. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  85639. }
  85640. for (index = 0; index < transparentSubMeshes.length; index++) {
  85641. _this._renderSubMesh(transparentSubMeshes.data[index]);
  85642. }
  85643. };
  85644. this._mainTexture.onClearObservable.add(function (engine) {
  85645. engine.clear(_this.neutralColor, true, true, true);
  85646. });
  85647. };
  85648. /**
  85649. * Checks for the readiness of the element composing the layer.
  85650. * @param subMesh the mesh to check for
  85651. * @param useInstances specify wether or not to use instances to render the mesh
  85652. * @param emissiveTexture the associated emissive texture used to generate the glow
  85653. * @return true if ready otherwise, false
  85654. */
  85655. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  85656. var material = subMesh.getMaterial();
  85657. if (!material) {
  85658. return false;
  85659. }
  85660. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  85661. return false;
  85662. }
  85663. var defines = [];
  85664. var attribs = [BABYLON.VertexBuffer.PositionKind];
  85665. var mesh = subMesh.getMesh();
  85666. var uv1 = false;
  85667. var uv2 = false;
  85668. // Alpha test
  85669. if (material && material.needAlphaTesting()) {
  85670. var alphaTexture = material.getAlphaTestTexture();
  85671. if (alphaTexture) {
  85672. defines.push("#define ALPHATEST");
  85673. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  85674. alphaTexture.coordinatesIndex === 1) {
  85675. defines.push("#define DIFFUSEUV2");
  85676. uv2 = true;
  85677. }
  85678. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85679. defines.push("#define DIFFUSEUV1");
  85680. uv1 = true;
  85681. }
  85682. }
  85683. }
  85684. // Emissive
  85685. if (emissiveTexture) {
  85686. defines.push("#define EMISSIVE");
  85687. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  85688. emissiveTexture.coordinatesIndex === 1) {
  85689. defines.push("#define EMISSIVEUV2");
  85690. uv2 = true;
  85691. }
  85692. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85693. defines.push("#define EMISSIVEUV1");
  85694. uv1 = true;
  85695. }
  85696. }
  85697. if (uv1) {
  85698. attribs.push(BABYLON.VertexBuffer.UVKind);
  85699. defines.push("#define UV1");
  85700. }
  85701. if (uv2) {
  85702. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85703. defines.push("#define UV2");
  85704. }
  85705. // Bones
  85706. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  85707. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  85708. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  85709. if (mesh.numBoneInfluencers > 4) {
  85710. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  85711. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  85712. }
  85713. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  85714. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  85715. }
  85716. else {
  85717. defines.push("#define NUM_BONE_INFLUENCERS 0");
  85718. }
  85719. // Morph targets
  85720. var manager = mesh.morphTargetManager;
  85721. var morphInfluencers = 0;
  85722. if (manager) {
  85723. if (manager.numInfluencers > 0) {
  85724. defines.push("#define MORPHTARGETS");
  85725. morphInfluencers = manager.numInfluencers;
  85726. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  85727. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  85728. }
  85729. }
  85730. // Instances
  85731. if (useInstances) {
  85732. defines.push("#define INSTANCES");
  85733. attribs.push("world0");
  85734. attribs.push("world1");
  85735. attribs.push("world2");
  85736. attribs.push("world3");
  85737. }
  85738. // Get correct effect
  85739. var join = defines.join("\n");
  85740. if (this._cachedDefines !== join) {
  85741. this._cachedDefines = join;
  85742. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  85743. }
  85744. return this._effectLayerMapGenerationEffect.isReady();
  85745. };
  85746. /**
  85747. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  85748. */
  85749. EffectLayer.prototype.render = function () {
  85750. var currentEffect = this._mergeEffect;
  85751. // Check
  85752. if (!currentEffect.isReady())
  85753. return;
  85754. for (var i = 0; i < this._postProcesses.length; i++) {
  85755. if (!this._postProcesses[i].isReady()) {
  85756. return;
  85757. }
  85758. }
  85759. var engine = this._scene.getEngine();
  85760. this.onBeforeComposeObservable.notifyObservers(this);
  85761. // Render
  85762. engine.enableEffect(currentEffect);
  85763. engine.setState(false);
  85764. // VBOs
  85765. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  85766. // Cache
  85767. var previousAlphaMode = engine.getAlphaMode();
  85768. // Go Blend.
  85769. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  85770. // Blends the map on the main canvas.
  85771. this._internalRender(currentEffect);
  85772. // Restore Alpha
  85773. engine.setAlphaMode(previousAlphaMode);
  85774. this.onAfterComposeObservable.notifyObservers(this);
  85775. // Handle size changes.
  85776. var size = this._mainTexture.getSize();
  85777. this._setMainTextureSize();
  85778. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  85779. // Recreate RTT and post processes on size change.
  85780. this.onSizeChangedObservable.notifyObservers(this);
  85781. this._disposeTextureAndPostProcesses();
  85782. this._createMainTexture();
  85783. this._createTextureAndPostProcesses();
  85784. }
  85785. };
  85786. /**
  85787. * Determine if a given mesh will be used in the current effect.
  85788. * @param mesh mesh to test
  85789. * @returns true if the mesh will be used
  85790. */
  85791. EffectLayer.prototype.hasMesh = function (mesh) {
  85792. return true;
  85793. };
  85794. /**
  85795. * Returns true if the layer contains information to display, otherwise false.
  85796. * @returns true if the glow layer should be rendered
  85797. */
  85798. EffectLayer.prototype.shouldRender = function () {
  85799. return this.isEnabled && this._shouldRender;
  85800. };
  85801. /**
  85802. * Returns true if the mesh should render, otherwise false.
  85803. * @param mesh The mesh to render
  85804. * @returns true if it should render otherwise false
  85805. */
  85806. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  85807. return true;
  85808. };
  85809. /**
  85810. * Returns true if the mesh should render, otherwise false.
  85811. * @param mesh The mesh to render
  85812. * @returns true if it should render otherwise false
  85813. */
  85814. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  85815. return true;
  85816. };
  85817. /**
  85818. * Renders the submesh passed in parameter to the generation map.
  85819. */
  85820. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  85821. var _this = this;
  85822. if (!this.shouldRender()) {
  85823. return;
  85824. }
  85825. var material = subMesh.getMaterial();
  85826. var mesh = subMesh.getRenderingMesh();
  85827. var scene = this._scene;
  85828. var engine = scene.getEngine();
  85829. if (!material) {
  85830. return;
  85831. }
  85832. // Do not block in blend mode.
  85833. if (material.needAlphaBlendingForMesh(mesh)) {
  85834. return;
  85835. }
  85836. // Culling
  85837. engine.setState(material.backFaceCulling);
  85838. // Managing instances
  85839. var batch = mesh._getInstancesRenderList(subMesh._id);
  85840. if (batch.mustReturn) {
  85841. return;
  85842. }
  85843. // Early Exit per mesh
  85844. if (!this._shouldRenderMesh(mesh)) {
  85845. return;
  85846. }
  85847. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  85848. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  85849. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  85850. engine.enableEffect(this._effectLayerMapGenerationEffect);
  85851. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  85852. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  85853. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  85854. // Alpha test
  85855. if (material && material.needAlphaTesting()) {
  85856. var alphaTexture = material.getAlphaTestTexture();
  85857. if (alphaTexture) {
  85858. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  85859. var textureMatrix = alphaTexture.getTextureMatrix();
  85860. if (textureMatrix) {
  85861. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  85862. }
  85863. }
  85864. }
  85865. // Glow emissive only
  85866. if (this._emissiveTextureAndColor.texture) {
  85867. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  85868. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  85869. }
  85870. // Bones
  85871. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  85872. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  85873. }
  85874. // Morph targets
  85875. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  85876. // Draw
  85877. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  85878. }
  85879. else {
  85880. // Need to reset refresh rate of the shadowMap
  85881. this._mainTexture.resetRefreshCounter();
  85882. }
  85883. };
  85884. /**
  85885. * Rebuild the required buffers.
  85886. * @ignore Internal use only.
  85887. */
  85888. EffectLayer.prototype._rebuild = function () {
  85889. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85890. if (vb) {
  85891. vb._rebuild();
  85892. }
  85893. this._generateIndexBuffer();
  85894. };
  85895. /**
  85896. * Dispose only the render target textures and post process.
  85897. */
  85898. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  85899. this._mainTexture.dispose();
  85900. for (var i = 0; i < this._postProcesses.length; i++) {
  85901. if (this._postProcesses[i]) {
  85902. this._postProcesses[i].dispose();
  85903. }
  85904. }
  85905. this._postProcesses = [];
  85906. for (var i = 0; i < this._textures.length; i++) {
  85907. if (this._textures[i]) {
  85908. this._textures[i].dispose();
  85909. }
  85910. }
  85911. this._textures = [];
  85912. };
  85913. /**
  85914. * Dispose the highlight layer and free resources.
  85915. */
  85916. EffectLayer.prototype.dispose = function () {
  85917. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85918. if (vertexBuffer) {
  85919. vertexBuffer.dispose();
  85920. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85921. }
  85922. if (this._indexBuffer) {
  85923. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85924. this._indexBuffer = null;
  85925. }
  85926. // Clean textures and post processes
  85927. this._disposeTextureAndPostProcesses();
  85928. // Remove from scene
  85929. var index = this._scene.effectLayers.indexOf(this, 0);
  85930. if (index > -1) {
  85931. this._scene.effectLayers.splice(index, 1);
  85932. }
  85933. // Callback
  85934. this.onDisposeObservable.notifyObservers(this);
  85935. this.onDisposeObservable.clear();
  85936. this.onBeforeRenderMainTextureObservable.clear();
  85937. this.onBeforeComposeObservable.clear();
  85938. this.onAfterComposeObservable.clear();
  85939. this.onSizeChangedObservable.clear();
  85940. };
  85941. return EffectLayer;
  85942. }());
  85943. BABYLON.EffectLayer = EffectLayer;
  85944. })(BABYLON || (BABYLON = {}));
  85945. //# sourceMappingURL=babylon.effectLayer.js.map
  85946. "use strict";
  85947. var BABYLON;
  85948. (function (BABYLON) {
  85949. /**
  85950. * Special Glow Blur post process only blurring the alpha channel
  85951. * It enforces keeping the most luminous color in the color channel.
  85952. */
  85953. var GlowBlurPostProcess = /** @class */ (function (_super) {
  85954. __extends(GlowBlurPostProcess, _super);
  85955. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  85956. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  85957. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  85958. _this.direction = direction;
  85959. _this.kernel = kernel;
  85960. _this.onApplyObservable.add(function (effect) {
  85961. effect.setFloat2("screenSize", _this.width, _this.height);
  85962. effect.setVector2("direction", _this.direction);
  85963. effect.setFloat("blurWidth", _this.kernel);
  85964. });
  85965. return _this;
  85966. }
  85967. return GlowBlurPostProcess;
  85968. }(BABYLON.PostProcess));
  85969. /**
  85970. * The highlight layer Helps adding a glow effect around a mesh.
  85971. *
  85972. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  85973. * glowy meshes to your scene.
  85974. *
  85975. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  85976. */
  85977. var HighlightLayer = /** @class */ (function (_super) {
  85978. __extends(HighlightLayer, _super);
  85979. /**
  85980. * Instantiates a new highlight Layer and references it to the scene..
  85981. * @param name The name of the layer
  85982. * @param scene The scene to use the layer in
  85983. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  85984. */
  85985. function HighlightLayer(name, scene, options) {
  85986. var _this = _super.call(this, name, scene) || this;
  85987. _this.name = name;
  85988. /**
  85989. * Specifies whether or not the inner glow is ACTIVE in the layer.
  85990. */
  85991. _this.innerGlow = true;
  85992. /**
  85993. * Specifies whether or not the outer glow is ACTIVE in the layer.
  85994. */
  85995. _this.outerGlow = true;
  85996. /**
  85997. * An event triggered when the highlight layer is being blurred.
  85998. */
  85999. _this.onBeforeBlurObservable = new BABYLON.Observable();
  86000. /**
  86001. * An event triggered when the highlight layer has been blurred.
  86002. */
  86003. _this.onAfterBlurObservable = new BABYLON.Observable();
  86004. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  86005. _this._meshes = {};
  86006. _this._excludedMeshes = {};
  86007. _this.neutralColor = HighlightLayer.NeutralColor;
  86008. // Warn on stencil
  86009. if (!_this._engine.isStencilEnable) {
  86010. 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 }");
  86011. }
  86012. // Adapt options
  86013. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  86014. // Initialize the layer
  86015. _this._init({
  86016. alphaBlendingMode: _this._options.alphaBlendingMode,
  86017. camera: _this._options.camera,
  86018. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  86019. mainTextureRatio: _this._options.mainTextureRatio
  86020. });
  86021. // Do not render as long as no meshes have been added
  86022. _this._shouldRender = false;
  86023. return _this;
  86024. }
  86025. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  86026. /**
  86027. * Gets the horizontal size of the blur.
  86028. */
  86029. get: function () {
  86030. return this._horizontalBlurPostprocess.kernel;
  86031. },
  86032. /**
  86033. * Specifies the horizontal size of the blur.
  86034. */
  86035. set: function (value) {
  86036. this._horizontalBlurPostprocess.kernel = value;
  86037. },
  86038. enumerable: true,
  86039. configurable: true
  86040. });
  86041. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  86042. /**
  86043. * Gets the vertical size of the blur.
  86044. */
  86045. get: function () {
  86046. return this._verticalBlurPostprocess.kernel;
  86047. },
  86048. /**
  86049. * Specifies the vertical size of the blur.
  86050. */
  86051. set: function (value) {
  86052. this._verticalBlurPostprocess.kernel = value;
  86053. },
  86054. enumerable: true,
  86055. configurable: true
  86056. });
  86057. /**
  86058. * Get the effect name of the layer.
  86059. * @return The effect name
  86060. */
  86061. HighlightLayer.prototype.getEffectName = function () {
  86062. return HighlightLayer.EffectName;
  86063. };
  86064. /**
  86065. * Create the merge effect. This is the shader use to blit the information back
  86066. * to the main canvas at the end of the scene rendering.
  86067. */
  86068. HighlightLayer.prototype._createMergeEffect = function () {
  86069. // Effect
  86070. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  86071. };
  86072. /**
  86073. * Creates the render target textures and post processes used in the highlight layer.
  86074. */
  86075. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  86076. var _this = this;
  86077. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  86078. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  86079. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  86080. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  86081. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  86082. width: blurTextureWidth,
  86083. height: blurTextureHeight
  86084. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86085. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86086. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86087. this._blurTexture.anisotropicFilteringLevel = 16;
  86088. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  86089. this._blurTexture.renderParticles = false;
  86090. this._blurTexture.ignoreCameraViewport = true;
  86091. this._textures = [this._blurTexture];
  86092. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  86093. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86094. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  86095. effect.setTexture("textureSampler", _this._mainTexture);
  86096. });
  86097. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86098. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  86099. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  86100. });
  86101. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86102. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  86103. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  86104. });
  86105. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  86106. }
  86107. else {
  86108. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  86109. width: blurTextureWidth,
  86110. height: blurTextureHeight
  86111. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86112. this._horizontalBlurPostprocess.width = blurTextureWidth;
  86113. this._horizontalBlurPostprocess.height = blurTextureHeight;
  86114. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  86115. effect.setTexture("textureSampler", _this._mainTexture);
  86116. });
  86117. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  86118. width: blurTextureWidth,
  86119. height: blurTextureHeight
  86120. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86121. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  86122. }
  86123. this._mainTexture.onAfterUnbindObservable.add(function () {
  86124. _this.onBeforeBlurObservable.notifyObservers(_this);
  86125. var internalTexture = _this._blurTexture.getInternalTexture();
  86126. if (internalTexture) {
  86127. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  86128. }
  86129. _this.onAfterBlurObservable.notifyObservers(_this);
  86130. });
  86131. // Prevent autoClear.
  86132. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  86133. };
  86134. /**
  86135. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  86136. */
  86137. HighlightLayer.prototype.needStencil = function () {
  86138. return true;
  86139. };
  86140. /**
  86141. * Checks for the readiness of the element composing the layer.
  86142. * @param subMesh the mesh to check for
  86143. * @param useInstances specify wether or not to use instances to render the mesh
  86144. * @param emissiveTexture the associated emissive texture used to generate the glow
  86145. * @return true if ready otherwise, false
  86146. */
  86147. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  86148. var material = subMesh.getMaterial();
  86149. var mesh = subMesh.getRenderingMesh();
  86150. if (!material || !mesh || !this._meshes) {
  86151. return false;
  86152. }
  86153. var emissiveTexture = null;
  86154. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  86155. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  86156. emissiveTexture = material.emissiveTexture;
  86157. }
  86158. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  86159. };
  86160. /**
  86161. * Implementation specific of rendering the generating effect on the main canvas.
  86162. * @param effect The effect used to render through
  86163. */
  86164. HighlightLayer.prototype._internalRender = function (effect) {
  86165. // Texture
  86166. effect.setTexture("textureSampler", this._blurTexture);
  86167. // Cache
  86168. var engine = this._engine;
  86169. var previousStencilBuffer = engine.getStencilBuffer();
  86170. var previousStencilFunction = engine.getStencilFunction();
  86171. var previousStencilMask = engine.getStencilMask();
  86172. var previousStencilOperationPass = engine.getStencilOperationPass();
  86173. var previousStencilOperationFail = engine.getStencilOperationFail();
  86174. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  86175. var previousStencilReference = engine.getStencilFunctionReference();
  86176. // Stencil operations
  86177. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  86178. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  86179. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  86180. // Draw order
  86181. engine.setStencilMask(0x00);
  86182. engine.setStencilBuffer(true);
  86183. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  86184. // 2 passes inner outer
  86185. if (this.outerGlow) {
  86186. effect.setFloat("offset", 0);
  86187. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  86188. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86189. }
  86190. if (this.innerGlow) {
  86191. effect.setFloat("offset", 1);
  86192. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  86193. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86194. }
  86195. // Restore Cache
  86196. engine.setStencilFunction(previousStencilFunction);
  86197. engine.setStencilMask(previousStencilMask);
  86198. engine.setStencilBuffer(previousStencilBuffer);
  86199. engine.setStencilOperationPass(previousStencilOperationPass);
  86200. engine.setStencilOperationFail(previousStencilOperationFail);
  86201. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  86202. engine.setStencilFunctionReference(previousStencilReference);
  86203. };
  86204. /**
  86205. * Returns true if the layer contains information to display, otherwise false.
  86206. */
  86207. HighlightLayer.prototype.shouldRender = function () {
  86208. if (_super.prototype.shouldRender.call(this)) {
  86209. return this._meshes ? true : false;
  86210. }
  86211. return false;
  86212. };
  86213. /**
  86214. * Returns true if the mesh should render, otherwise false.
  86215. * @param mesh The mesh to render
  86216. * @returns true if it should render otherwise false
  86217. */
  86218. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  86219. // Excluded Mesh
  86220. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  86221. return false;
  86222. }
  86223. ;
  86224. return true;
  86225. };
  86226. /**
  86227. * Sets the required values for both the emissive texture and and the main color.
  86228. */
  86229. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  86230. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  86231. if (highlightLayerMesh) {
  86232. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  86233. }
  86234. else {
  86235. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  86236. }
  86237. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  86238. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  86239. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  86240. }
  86241. else {
  86242. this._emissiveTextureAndColor.texture = null;
  86243. }
  86244. };
  86245. /**
  86246. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  86247. * @param mesh The mesh to exclude from the highlight layer
  86248. */
  86249. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  86250. if (!this._excludedMeshes) {
  86251. return;
  86252. }
  86253. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  86254. if (!meshExcluded) {
  86255. this._excludedMeshes[mesh.uniqueId] = {
  86256. mesh: mesh,
  86257. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  86258. mesh.getEngine().setStencilBuffer(false);
  86259. }),
  86260. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  86261. mesh.getEngine().setStencilBuffer(true);
  86262. }),
  86263. };
  86264. }
  86265. };
  86266. /**
  86267. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  86268. * @param mesh The mesh to highlight
  86269. */
  86270. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  86271. if (!this._excludedMeshes) {
  86272. return;
  86273. }
  86274. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  86275. if (meshExcluded) {
  86276. if (meshExcluded.beforeRender) {
  86277. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  86278. }
  86279. if (meshExcluded.afterRender) {
  86280. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  86281. }
  86282. }
  86283. this._excludedMeshes[mesh.uniqueId] = null;
  86284. };
  86285. /**
  86286. * Determine if a given mesh will be highlighted by the current HighlightLayer
  86287. * @param mesh mesh to test
  86288. * @returns true if the mesh will be highlighted by the current HighlightLayer
  86289. */
  86290. HighlightLayer.prototype.hasMesh = function (mesh) {
  86291. if (!this._meshes) {
  86292. return false;
  86293. }
  86294. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  86295. };
  86296. /**
  86297. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  86298. * @param mesh The mesh to highlight
  86299. * @param color The color of the highlight
  86300. * @param glowEmissiveOnly Extract the glow from the emissive texture
  86301. */
  86302. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  86303. var _this = this;
  86304. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  86305. if (!this._meshes) {
  86306. return;
  86307. }
  86308. var meshHighlight = this._meshes[mesh.uniqueId];
  86309. if (meshHighlight) {
  86310. meshHighlight.color = color;
  86311. }
  86312. else {
  86313. this._meshes[mesh.uniqueId] = {
  86314. mesh: mesh,
  86315. color: color,
  86316. // Lambda required for capture due to Observable this context
  86317. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  86318. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  86319. _this._defaultStencilReference(mesh);
  86320. }
  86321. else {
  86322. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  86323. }
  86324. }),
  86325. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  86326. glowEmissiveOnly: glowEmissiveOnly
  86327. };
  86328. }
  86329. this._shouldRender = true;
  86330. };
  86331. /**
  86332. * Remove a mesh from the highlight layer in order to make it stop glowing.
  86333. * @param mesh The mesh to highlight
  86334. */
  86335. HighlightLayer.prototype.removeMesh = function (mesh) {
  86336. if (!this._meshes) {
  86337. return;
  86338. }
  86339. var meshHighlight = this._meshes[mesh.uniqueId];
  86340. if (meshHighlight) {
  86341. if (meshHighlight.observerHighlight) {
  86342. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  86343. }
  86344. if (meshHighlight.observerDefault) {
  86345. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  86346. }
  86347. delete this._meshes[mesh.uniqueId];
  86348. }
  86349. this._shouldRender = false;
  86350. for (var meshHighlightToCheck in this._meshes) {
  86351. if (this._meshes[meshHighlightToCheck]) {
  86352. this._shouldRender = true;
  86353. break;
  86354. }
  86355. }
  86356. };
  86357. /**
  86358. * Force the stencil to the normal expected value for none glowing parts
  86359. */
  86360. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  86361. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  86362. };
  86363. /**
  86364. * Free any resources and references associated to a mesh.
  86365. * Internal use
  86366. * @param mesh The mesh to free.
  86367. */
  86368. HighlightLayer.prototype._disposeMesh = function (mesh) {
  86369. this.removeMesh(mesh);
  86370. this.removeExcludedMesh(mesh);
  86371. };
  86372. /**
  86373. * Dispose the highlight layer and free resources.
  86374. */
  86375. HighlightLayer.prototype.dispose = function () {
  86376. if (this._meshes) {
  86377. // Clean mesh references
  86378. for (var id in this._meshes) {
  86379. var meshHighlight = this._meshes[id];
  86380. if (meshHighlight && meshHighlight.mesh) {
  86381. if (meshHighlight.observerHighlight) {
  86382. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  86383. }
  86384. if (meshHighlight.observerDefault) {
  86385. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  86386. }
  86387. }
  86388. }
  86389. this._meshes = null;
  86390. }
  86391. if (this._excludedMeshes) {
  86392. for (var id in this._excludedMeshes) {
  86393. var meshHighlight = this._excludedMeshes[id];
  86394. if (meshHighlight) {
  86395. if (meshHighlight.beforeRender) {
  86396. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  86397. }
  86398. if (meshHighlight.afterRender) {
  86399. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  86400. }
  86401. }
  86402. }
  86403. this._excludedMeshes = null;
  86404. }
  86405. _super.prototype.dispose.call(this);
  86406. };
  86407. /**
  86408. * Effect Name of the highlight layer.
  86409. */
  86410. HighlightLayer.EffectName = "HighlightLayer";
  86411. /**
  86412. * The neutral color used during the preparation of the glow effect.
  86413. * This is black by default as the blend operation is a blend operation.
  86414. */
  86415. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  86416. /**
  86417. * Stencil value used for glowing meshes.
  86418. */
  86419. HighlightLayer.GlowingMeshStencilReference = 0x02;
  86420. /**
  86421. * Stencil value used for the other meshes in the scene.
  86422. */
  86423. HighlightLayer.NormalMeshStencilReference = 0x01;
  86424. return HighlightLayer;
  86425. }(BABYLON.EffectLayer));
  86426. BABYLON.HighlightLayer = HighlightLayer;
  86427. })(BABYLON || (BABYLON = {}));
  86428. //# sourceMappingURL=babylon.highlightLayer.js.map
  86429. "use strict";
  86430. var BABYLON;
  86431. (function (BABYLON) {
  86432. /**
  86433. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  86434. *
  86435. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  86436. * glowy meshes to your scene.
  86437. *
  86438. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  86439. */
  86440. var GlowLayer = /** @class */ (function (_super) {
  86441. __extends(GlowLayer, _super);
  86442. /**
  86443. * Instantiates a new glow Layer and references it to the scene.
  86444. * @param name The name of the layer
  86445. * @param scene The scene to use the layer in
  86446. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  86447. */
  86448. function GlowLayer(name, scene, options) {
  86449. var _this = _super.call(this, name, scene) || this;
  86450. _this.name = name;
  86451. _this._intensity = 1.0;
  86452. _this._includedOnlyMeshes = [];
  86453. _this._excludedMeshes = [];
  86454. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  86455. // Adapt options
  86456. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  86457. // Initialize the layer
  86458. _this._init({
  86459. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  86460. camera: _this._options.camera,
  86461. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  86462. mainTextureRatio: _this._options.mainTextureRatio
  86463. });
  86464. return _this;
  86465. }
  86466. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  86467. /**
  86468. * Gets the kernel size of the blur.
  86469. */
  86470. get: function () {
  86471. return this._horizontalBlurPostprocess1.kernel;
  86472. },
  86473. /**
  86474. * Sets the kernel size of the blur.
  86475. */
  86476. set: function (value) {
  86477. this._horizontalBlurPostprocess1.kernel = value;
  86478. this._verticalBlurPostprocess1.kernel = value;
  86479. this._horizontalBlurPostprocess2.kernel = value;
  86480. this._verticalBlurPostprocess2.kernel = value;
  86481. },
  86482. enumerable: true,
  86483. configurable: true
  86484. });
  86485. Object.defineProperty(GlowLayer.prototype, "intensity", {
  86486. /**
  86487. * Gets the glow intensity.
  86488. */
  86489. get: function () {
  86490. return this._intensity;
  86491. },
  86492. /**
  86493. * Sets the glow intensity.
  86494. */
  86495. set: function (value) {
  86496. this._intensity = value;
  86497. },
  86498. enumerable: true,
  86499. configurable: true
  86500. });
  86501. /**
  86502. * Get the effect name of the layer.
  86503. * @return The effect name
  86504. */
  86505. GlowLayer.prototype.getEffectName = function () {
  86506. return GlowLayer.EffectName;
  86507. };
  86508. /**
  86509. * Create the merge effect. This is the shader use to blit the information back
  86510. * to the main canvas at the end of the scene rendering.
  86511. */
  86512. GlowLayer.prototype._createMergeEffect = function () {
  86513. // Effect
  86514. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  86515. };
  86516. /**
  86517. * Creates the render target textures and post processes used in the glow layer.
  86518. */
  86519. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  86520. var _this = this;
  86521. var blurTextureWidth = this._mainTextureDesiredSize.width;
  86522. var blurTextureHeight = this._mainTextureDesiredSize.height;
  86523. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  86524. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  86525. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  86526. width: blurTextureWidth,
  86527. height: blurTextureHeight
  86528. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86529. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86530. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86531. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86532. this._blurTexture1.renderParticles = false;
  86533. this._blurTexture1.ignoreCameraViewport = true;
  86534. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  86535. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  86536. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  86537. width: blurTextureWidth2,
  86538. height: blurTextureHeight2
  86539. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86540. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86541. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86542. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86543. this._blurTexture2.renderParticles = false;
  86544. this._blurTexture2.ignoreCameraViewport = true;
  86545. this._textures = [this._blurTexture1, this._blurTexture2];
  86546. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  86547. width: blurTextureWidth,
  86548. height: blurTextureHeight
  86549. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86550. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  86551. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  86552. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  86553. effect.setTexture("textureSampler", _this._mainTexture);
  86554. });
  86555. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  86556. width: blurTextureWidth,
  86557. height: blurTextureHeight
  86558. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86559. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  86560. width: blurTextureWidth2,
  86561. height: blurTextureHeight2
  86562. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86563. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  86564. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  86565. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  86566. effect.setTexture("textureSampler", _this._blurTexture1);
  86567. });
  86568. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  86569. width: blurTextureWidth2,
  86570. height: blurTextureHeight2
  86571. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86572. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  86573. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  86574. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  86575. this._mainTexture.samples = this._options.mainTextureSamples;
  86576. this._mainTexture.onAfterUnbindObservable.add(function () {
  86577. var internalTexture = _this._blurTexture1.getInternalTexture();
  86578. if (internalTexture) {
  86579. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  86580. internalTexture = _this._blurTexture2.getInternalTexture();
  86581. if (internalTexture) {
  86582. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  86583. }
  86584. }
  86585. });
  86586. // Prevent autoClear.
  86587. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  86588. };
  86589. /**
  86590. * Checks for the readiness of the element composing the layer.
  86591. * @param subMesh the mesh to check for
  86592. * @param useInstances specify wether or not to use instances to render the mesh
  86593. * @param emissiveTexture the associated emissive texture used to generate the glow
  86594. * @return true if ready otherwise, false
  86595. */
  86596. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  86597. var material = subMesh.getMaterial();
  86598. var mesh = subMesh.getRenderingMesh();
  86599. if (!material || !mesh) {
  86600. return false;
  86601. }
  86602. var emissiveTexture = material.emissiveTexture;
  86603. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  86604. };
  86605. /**
  86606. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  86607. */
  86608. GlowLayer.prototype.needStencil = function () {
  86609. return false;
  86610. };
  86611. /**
  86612. * Implementation specific of rendering the generating effect on the main canvas.
  86613. * @param effect The effect used to render through
  86614. */
  86615. GlowLayer.prototype._internalRender = function (effect) {
  86616. // Texture
  86617. effect.setTexture("textureSampler", this._blurTexture1);
  86618. effect.setTexture("textureSampler2", this._blurTexture2);
  86619. effect.setFloat("offset", this._intensity);
  86620. // Cache
  86621. var engine = this._engine;
  86622. var previousStencilBuffer = engine.getStencilBuffer();
  86623. // Draw order
  86624. engine.setStencilBuffer(false);
  86625. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86626. // Draw order
  86627. engine.setStencilBuffer(previousStencilBuffer);
  86628. };
  86629. /**
  86630. * Sets the required values for both the emissive texture and and the main color.
  86631. */
  86632. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  86633. var textureLevel = 1.0;
  86634. if (this.customEmissiveTextureSelector) {
  86635. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  86636. }
  86637. else {
  86638. if (material) {
  86639. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  86640. if (this._emissiveTextureAndColor.texture) {
  86641. textureLevel = this._emissiveTextureAndColor.texture.level;
  86642. }
  86643. }
  86644. else {
  86645. this._emissiveTextureAndColor.texture = null;
  86646. }
  86647. }
  86648. if (this.customEmissiveColorSelector) {
  86649. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  86650. }
  86651. else {
  86652. if (material.emissiveColor) {
  86653. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  86654. }
  86655. else {
  86656. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  86657. }
  86658. }
  86659. };
  86660. /**
  86661. * Returns true if the mesh should render, otherwise false.
  86662. * @param mesh The mesh to render
  86663. * @returns true if it should render otherwise false
  86664. */
  86665. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  86666. return this.hasMesh(mesh);
  86667. };
  86668. /**
  86669. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  86670. * @param mesh The mesh to exclude from the glow layer
  86671. */
  86672. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  86673. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  86674. this._excludedMeshes.push(mesh.uniqueId);
  86675. }
  86676. };
  86677. /**
  86678. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  86679. * @param mesh The mesh to remove
  86680. */
  86681. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  86682. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  86683. if (index !== -1) {
  86684. this._excludedMeshes.splice(index, 1);
  86685. }
  86686. };
  86687. /**
  86688. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  86689. * @param mesh The mesh to include in the glow layer
  86690. */
  86691. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  86692. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  86693. this._includedOnlyMeshes.push(mesh.uniqueId);
  86694. }
  86695. };
  86696. /**
  86697. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  86698. * @param mesh The mesh to remove
  86699. */
  86700. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  86701. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  86702. if (index !== -1) {
  86703. this._includedOnlyMeshes.splice(index, 1);
  86704. }
  86705. };
  86706. /**
  86707. * Determine if a given mesh will be used in the glow layer
  86708. * @param mesh The mesh to test
  86709. * @returns true if the mesh will be highlighted by the current glow layer
  86710. */
  86711. GlowLayer.prototype.hasMesh = function (mesh) {
  86712. // Included Mesh
  86713. if (this._includedOnlyMeshes.length) {
  86714. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  86715. }
  86716. ;
  86717. // Excluded Mesh
  86718. if (this._excludedMeshes.length) {
  86719. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  86720. }
  86721. ;
  86722. return true;
  86723. };
  86724. /**
  86725. * Free any resources and references associated to a mesh.
  86726. * Internal use
  86727. * @param mesh The mesh to free.
  86728. */
  86729. GlowLayer.prototype._disposeMesh = function (mesh) {
  86730. this.removeIncludedOnlyMesh(mesh);
  86731. this.removeExcludedMesh(mesh);
  86732. };
  86733. /**
  86734. * Effect Name of the layer.
  86735. */
  86736. GlowLayer.EffectName = "GlowLayer";
  86737. /**
  86738. * The default blur kernel size used for the glow.
  86739. */
  86740. GlowLayer.DefaultBlurKernelSize = 32;
  86741. /**
  86742. * The default texture size ratio used for the glow.
  86743. */
  86744. GlowLayer.DefaultTextureRatio = 0.5;
  86745. return GlowLayer;
  86746. }(BABYLON.EffectLayer));
  86747. BABYLON.GlowLayer = GlowLayer;
  86748. })(BABYLON || (BABYLON = {}));
  86749. //# sourceMappingURL=babylon.glowLayer.js.map
  86750. "use strict";
  86751. var BABYLON;
  86752. (function (BABYLON) {
  86753. /**
  86754. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  86755. */
  86756. var AssetTaskState;
  86757. (function (AssetTaskState) {
  86758. /**
  86759. * Initialization
  86760. */
  86761. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  86762. /**
  86763. * Running
  86764. */
  86765. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  86766. /**
  86767. * Done
  86768. */
  86769. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  86770. /**
  86771. * Error
  86772. */
  86773. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  86774. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  86775. /**
  86776. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  86777. */
  86778. var AbstractAssetTask = /** @class */ (function () {
  86779. /**
  86780. * Creates a new {BABYLON.AssetsManager}
  86781. * @param name defines the name of the task
  86782. */
  86783. function AbstractAssetTask(
  86784. /**
  86785. * Task name
  86786. */ name) {
  86787. this.name = name;
  86788. this._isCompleted = false;
  86789. this._taskState = AssetTaskState.INIT;
  86790. }
  86791. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  86792. /**
  86793. * Get if the task is completed
  86794. */
  86795. get: function () {
  86796. return this._isCompleted;
  86797. },
  86798. enumerable: true,
  86799. configurable: true
  86800. });
  86801. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  86802. /**
  86803. * Gets the current state of the task
  86804. */
  86805. get: function () {
  86806. return this._taskState;
  86807. },
  86808. enumerable: true,
  86809. configurable: true
  86810. });
  86811. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  86812. /**
  86813. * Gets the current error object (if task is in error)
  86814. */
  86815. get: function () {
  86816. return this._errorObject;
  86817. },
  86818. enumerable: true,
  86819. configurable: true
  86820. });
  86821. /**
  86822. * Internal only
  86823. * @ignore
  86824. */
  86825. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  86826. if (this._errorObject) {
  86827. return;
  86828. }
  86829. this._errorObject = {
  86830. message: message,
  86831. exception: exception
  86832. };
  86833. };
  86834. /**
  86835. * Execute the current task
  86836. * @param scene defines the scene where you want your assets to be loaded
  86837. * @param onSuccess is a callback called when the task is successfully executed
  86838. * @param onError is a callback called if an error occurs
  86839. */
  86840. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  86841. var _this = this;
  86842. this._taskState = AssetTaskState.RUNNING;
  86843. this.runTask(scene, function () {
  86844. _this.onDoneCallback(onSuccess, onError);
  86845. }, function (msg, exception) {
  86846. _this.onErrorCallback(onError, msg, exception);
  86847. });
  86848. };
  86849. /**
  86850. * Execute the current task
  86851. * @param scene defines the scene where you want your assets to be loaded
  86852. * @param onSuccess is a callback called when the task is successfully executed
  86853. * @param onError is a callback called if an error occurs
  86854. */
  86855. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86856. throw new Error("runTask is not implemented");
  86857. };
  86858. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  86859. this._taskState = AssetTaskState.ERROR;
  86860. this._errorObject = {
  86861. message: message,
  86862. exception: exception
  86863. };
  86864. if (this.onError) {
  86865. this.onError(this, message, exception);
  86866. }
  86867. onError();
  86868. };
  86869. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  86870. try {
  86871. this._taskState = AssetTaskState.DONE;
  86872. this._isCompleted = true;
  86873. if (this.onSuccess) {
  86874. this.onSuccess(this);
  86875. }
  86876. onSuccess();
  86877. }
  86878. catch (e) {
  86879. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  86880. }
  86881. };
  86882. return AbstractAssetTask;
  86883. }());
  86884. BABYLON.AbstractAssetTask = AbstractAssetTask;
  86885. /**
  86886. * Class used to share progress information about assets loading
  86887. */
  86888. var AssetsProgressEvent = /** @class */ (function () {
  86889. /**
  86890. * Creates a {BABYLON.AssetsProgressEvent}
  86891. * @param remainingCount defines the number of remaining tasks to process
  86892. * @param totalCount defines the total number of tasks
  86893. * @param task defines the task that was just processed
  86894. */
  86895. function AssetsProgressEvent(remainingCount, totalCount, task) {
  86896. this.remainingCount = remainingCount;
  86897. this.totalCount = totalCount;
  86898. this.task = task;
  86899. }
  86900. return AssetsProgressEvent;
  86901. }());
  86902. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  86903. /**
  86904. * Define a task used by {BABYLON.AssetsManager} to load meshes
  86905. */
  86906. var MeshAssetTask = /** @class */ (function (_super) {
  86907. __extends(MeshAssetTask, _super);
  86908. /**
  86909. * Creates a new {BABYLON.MeshAssetTask}
  86910. * @param name defines the name of the task
  86911. * @param meshesNames defines the list of mesh's names you want to load
  86912. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  86913. * @param sceneFilename defines the filename of the scene to load from
  86914. */
  86915. function MeshAssetTask(
  86916. /**
  86917. * Defines the name of the task
  86918. */
  86919. name,
  86920. /**
  86921. * Defines the list of mesh's names you want to load
  86922. */
  86923. meshesNames,
  86924. /**
  86925. * Defines the root url to use as a base to load your meshes and associated resources
  86926. */
  86927. rootUrl,
  86928. /**
  86929. * Defines the filename of the scene to load from
  86930. */
  86931. sceneFilename) {
  86932. var _this = _super.call(this, name) || this;
  86933. _this.name = name;
  86934. _this.meshesNames = meshesNames;
  86935. _this.rootUrl = rootUrl;
  86936. _this.sceneFilename = sceneFilename;
  86937. return _this;
  86938. }
  86939. /**
  86940. * Execute the current task
  86941. * @param scene defines the scene where you want your assets to be loaded
  86942. * @param onSuccess is a callback called when the task is successfully executed
  86943. * @param onError is a callback called if an error occurs
  86944. */
  86945. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86946. var _this = this;
  86947. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  86948. _this.loadedMeshes = meshes;
  86949. _this.loadedParticleSystems = particleSystems;
  86950. _this.loadedSkeletons = skeletons;
  86951. onSuccess();
  86952. }, null, function (scene, message, exception) {
  86953. onError(message, exception);
  86954. });
  86955. };
  86956. return MeshAssetTask;
  86957. }(AbstractAssetTask));
  86958. BABYLON.MeshAssetTask = MeshAssetTask;
  86959. /**
  86960. * Define a task used by {BABYLON.AssetsManager} to load text content
  86961. */
  86962. var TextFileAssetTask = /** @class */ (function (_super) {
  86963. __extends(TextFileAssetTask, _super);
  86964. /**
  86965. * Creates a new TextFileAssetTask object
  86966. * @param name defines the name of the task
  86967. * @param url defines the location of the file to load
  86968. */
  86969. function TextFileAssetTask(
  86970. /**
  86971. * Defines the name of the task
  86972. */
  86973. name,
  86974. /**
  86975. * Defines the location of the file to load
  86976. */
  86977. url) {
  86978. var _this = _super.call(this, name) || this;
  86979. _this.name = name;
  86980. _this.url = url;
  86981. return _this;
  86982. }
  86983. /**
  86984. * Execute the current task
  86985. * @param scene defines the scene where you want your assets to be loaded
  86986. * @param onSuccess is a callback called when the task is successfully executed
  86987. * @param onError is a callback called if an error occurs
  86988. */
  86989. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86990. var _this = this;
  86991. scene._loadFile(this.url, function (data) {
  86992. _this.text = data;
  86993. onSuccess();
  86994. }, undefined, false, false, function (request, exception) {
  86995. if (request) {
  86996. onError(request.status + " " + request.statusText, exception);
  86997. }
  86998. });
  86999. };
  87000. return TextFileAssetTask;
  87001. }(AbstractAssetTask));
  87002. BABYLON.TextFileAssetTask = TextFileAssetTask;
  87003. /**
  87004. * Define a task used by {BABYLON.AssetsManager} to load binary data
  87005. */
  87006. var BinaryFileAssetTask = /** @class */ (function (_super) {
  87007. __extends(BinaryFileAssetTask, _super);
  87008. /**
  87009. * Creates a new BinaryFileAssetTask object
  87010. * @param name defines the name of the new task
  87011. * @param url defines the location of the file to load
  87012. */
  87013. function BinaryFileAssetTask(
  87014. /**
  87015. * Defines the name of the task
  87016. */
  87017. name,
  87018. /**
  87019. * Defines the location of the file to load
  87020. */
  87021. url) {
  87022. var _this = _super.call(this, name) || this;
  87023. _this.name = name;
  87024. _this.url = url;
  87025. return _this;
  87026. }
  87027. /**
  87028. * Execute the current task
  87029. * @param scene defines the scene where you want your assets to be loaded
  87030. * @param onSuccess is a callback called when the task is successfully executed
  87031. * @param onError is a callback called if an error occurs
  87032. */
  87033. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87034. var _this = this;
  87035. scene._loadFile(this.url, function (data) {
  87036. _this.data = data;
  87037. onSuccess();
  87038. }, undefined, true, true, function (request, exception) {
  87039. if (request) {
  87040. onError(request.status + " " + request.statusText, exception);
  87041. }
  87042. });
  87043. };
  87044. return BinaryFileAssetTask;
  87045. }(AbstractAssetTask));
  87046. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  87047. /**
  87048. * Define a task used by {BABYLON.AssetsManager} to load images
  87049. */
  87050. var ImageAssetTask = /** @class */ (function (_super) {
  87051. __extends(ImageAssetTask, _super);
  87052. /**
  87053. * Creates a new ImageAssetTask
  87054. * @param name defines the name of the task
  87055. * @param url defines the location of the image to load
  87056. */
  87057. function ImageAssetTask(
  87058. /**
  87059. * Defines the name of the task
  87060. */
  87061. name,
  87062. /**
  87063. * Defines the location of the image to load
  87064. */
  87065. url) {
  87066. var _this = _super.call(this, name) || this;
  87067. _this.name = name;
  87068. _this.url = url;
  87069. return _this;
  87070. }
  87071. /**
  87072. * Execute the current task
  87073. * @param scene defines the scene where you want your assets to be loaded
  87074. * @param onSuccess is a callback called when the task is successfully executed
  87075. * @param onError is a callback called if an error occurs
  87076. */
  87077. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87078. var _this = this;
  87079. var img = new Image();
  87080. BABYLON.Tools.SetCorsBehavior(this.url, img);
  87081. img.onload = function () {
  87082. _this.image = img;
  87083. onSuccess();
  87084. };
  87085. img.onerror = function (err) {
  87086. onError("Error loading image", err);
  87087. };
  87088. img.src = this.url;
  87089. };
  87090. return ImageAssetTask;
  87091. }(AbstractAssetTask));
  87092. BABYLON.ImageAssetTask = ImageAssetTask;
  87093. /**
  87094. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  87095. */
  87096. var TextureAssetTask = /** @class */ (function (_super) {
  87097. __extends(TextureAssetTask, _super);
  87098. /**
  87099. * Creates a new TextureAssetTask object
  87100. * @param name defines the name of the task
  87101. * @param url defines the location of the file to load
  87102. * @param noMipmap defines if mipmap should not be generated (default is false)
  87103. * @param invertY defines if texture must be inverted on Y axis (default is false)
  87104. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  87105. */
  87106. function TextureAssetTask(
  87107. /**
  87108. * Defines the name of the task
  87109. */
  87110. name,
  87111. /**
  87112. * Defines the location of the file to load
  87113. */
  87114. url,
  87115. /**
  87116. * Defines if mipmap should not be generated (default is false)
  87117. */
  87118. noMipmap,
  87119. /**
  87120. * Defines if texture must be inverted on Y axis (default is false)
  87121. */
  87122. invertY,
  87123. /**
  87124. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  87125. */
  87126. samplingMode) {
  87127. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  87128. var _this = _super.call(this, name) || this;
  87129. _this.name = name;
  87130. _this.url = url;
  87131. _this.noMipmap = noMipmap;
  87132. _this.invertY = invertY;
  87133. _this.samplingMode = samplingMode;
  87134. return _this;
  87135. }
  87136. /**
  87137. * Execute the current task
  87138. * @param scene defines the scene where you want your assets to be loaded
  87139. * @param onSuccess is a callback called when the task is successfully executed
  87140. * @param onError is a callback called if an error occurs
  87141. */
  87142. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87143. var onload = function () {
  87144. onSuccess();
  87145. };
  87146. var onerror = function (message, exception) {
  87147. onError(message, exception);
  87148. };
  87149. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  87150. };
  87151. return TextureAssetTask;
  87152. }(AbstractAssetTask));
  87153. BABYLON.TextureAssetTask = TextureAssetTask;
  87154. /**
  87155. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  87156. */
  87157. var CubeTextureAssetTask = /** @class */ (function (_super) {
  87158. __extends(CubeTextureAssetTask, _super);
  87159. /**
  87160. * Creates a new CubeTextureAssetTask
  87161. * @param name defines the name of the task
  87162. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  87163. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  87164. * @param noMipmap defines if mipmaps should not be generated (default is false)
  87165. * @param files defines the explicit list of files (undefined by default)
  87166. */
  87167. function CubeTextureAssetTask(
  87168. /**
  87169. * Defines the name of the task
  87170. */
  87171. name,
  87172. /**
  87173. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  87174. */
  87175. url,
  87176. /**
  87177. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  87178. */
  87179. extensions,
  87180. /**
  87181. * Defines if mipmaps should not be generated (default is false)
  87182. */
  87183. noMipmap,
  87184. /**
  87185. * Defines the explicit list of files (undefined by default)
  87186. */
  87187. files) {
  87188. var _this = _super.call(this, name) || this;
  87189. _this.name = name;
  87190. _this.url = url;
  87191. _this.extensions = extensions;
  87192. _this.noMipmap = noMipmap;
  87193. _this.files = files;
  87194. return _this;
  87195. }
  87196. /**
  87197. * Execute the current task
  87198. * @param scene defines the scene where you want your assets to be loaded
  87199. * @param onSuccess is a callback called when the task is successfully executed
  87200. * @param onError is a callback called if an error occurs
  87201. */
  87202. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87203. var onload = function () {
  87204. onSuccess();
  87205. };
  87206. var onerror = function (message, exception) {
  87207. onError(message, exception);
  87208. };
  87209. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  87210. };
  87211. return CubeTextureAssetTask;
  87212. }(AbstractAssetTask));
  87213. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  87214. /**
  87215. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  87216. */
  87217. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  87218. __extends(HDRCubeTextureAssetTask, _super);
  87219. /**
  87220. * Creates a new HDRCubeTextureAssetTask object
  87221. * @param name defines the name of the task
  87222. * @param url defines the location of the file to load
  87223. * @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.
  87224. * @param noMipmap defines if mipmaps should not be generated (default is false)
  87225. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  87226. * @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)
  87227. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  87228. */
  87229. function HDRCubeTextureAssetTask(
  87230. /**
  87231. * Defines the name of the task
  87232. */
  87233. name,
  87234. /**
  87235. * Defines the location of the file to load
  87236. */
  87237. url,
  87238. /**
  87239. * 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.
  87240. */
  87241. size,
  87242. /**
  87243. * Defines if mipmaps should not be generated (default is false)
  87244. */
  87245. noMipmap,
  87246. /**
  87247. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  87248. */
  87249. generateHarmonics,
  87250. /**
  87251. * 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)
  87252. */
  87253. useInGammaSpace,
  87254. /**
  87255. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  87256. */
  87257. usePMREMGenerator) {
  87258. if (noMipmap === void 0) { noMipmap = false; }
  87259. if (generateHarmonics === void 0) { generateHarmonics = true; }
  87260. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  87261. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  87262. var _this = _super.call(this, name) || this;
  87263. _this.name = name;
  87264. _this.url = url;
  87265. _this.size = size;
  87266. _this.noMipmap = noMipmap;
  87267. _this.generateHarmonics = generateHarmonics;
  87268. _this.useInGammaSpace = useInGammaSpace;
  87269. _this.usePMREMGenerator = usePMREMGenerator;
  87270. return _this;
  87271. }
  87272. /**
  87273. * Execute the current task
  87274. * @param scene defines the scene where you want your assets to be loaded
  87275. * @param onSuccess is a callback called when the task is successfully executed
  87276. * @param onError is a callback called if an error occurs
  87277. */
  87278. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  87279. var onload = function () {
  87280. onSuccess();
  87281. };
  87282. var onerror = function (message, exception) {
  87283. onError(message, exception);
  87284. };
  87285. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  87286. };
  87287. return HDRCubeTextureAssetTask;
  87288. }(AbstractAssetTask));
  87289. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  87290. /**
  87291. * This class can be used to easily import assets into a scene
  87292. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  87293. */
  87294. var AssetsManager = /** @class */ (function () {
  87295. /**
  87296. * Creates a new AssetsManager
  87297. * @param scene defines the scene to work on
  87298. */
  87299. function AssetsManager(scene) {
  87300. this._isLoading = false;
  87301. this._tasks = new Array();
  87302. this._waitingTasksCount = 0;
  87303. this._totalTasksCount = 0;
  87304. /**
  87305. * Observable called when all tasks are processed
  87306. */
  87307. this.onTaskSuccessObservable = new BABYLON.Observable();
  87308. /**
  87309. * Observable called when a task had an error
  87310. */
  87311. this.onTaskErrorObservable = new BABYLON.Observable();
  87312. /**
  87313. * Observable called when a task is successful
  87314. */
  87315. this.onTasksDoneObservable = new BABYLON.Observable();
  87316. /**
  87317. * Observable called when a task is done (whatever the result is)
  87318. */
  87319. this.onProgressObservable = new BABYLON.Observable();
  87320. /**
  87321. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  87322. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  87323. */
  87324. this.useDefaultLoadingScreen = true;
  87325. this._scene = scene;
  87326. }
  87327. /**
  87328. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  87329. * @param taskName defines the name of the new task
  87330. * @param meshesNames defines the name of meshes to load
  87331. * @param rootUrl defines the root url to use to locate files
  87332. * @param sceneFilename defines the filename of the scene file
  87333. * @returns a new {BABYLON.MeshAssetTask} object
  87334. */
  87335. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  87336. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  87337. this._tasks.push(task);
  87338. return task;
  87339. };
  87340. /**
  87341. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  87342. * @param taskName defines the name of the new task
  87343. * @param url defines the url of the file to load
  87344. * @returns a new {BABYLON.TextFileAssetTask} object
  87345. */
  87346. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  87347. var task = new TextFileAssetTask(taskName, url);
  87348. this._tasks.push(task);
  87349. return task;
  87350. };
  87351. /**
  87352. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  87353. * @param taskName defines the name of the new task
  87354. * @param url defines the url of the file to load
  87355. * @returns a new {BABYLON.BinaryFileAssetTask} object
  87356. */
  87357. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  87358. var task = new BinaryFileAssetTask(taskName, url);
  87359. this._tasks.push(task);
  87360. return task;
  87361. };
  87362. /**
  87363. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  87364. * @param taskName defines the name of the new task
  87365. * @param url defines the url of the file to load
  87366. * @returns a new {BABYLON.ImageAssetTask} object
  87367. */
  87368. AssetsManager.prototype.addImageTask = function (taskName, url) {
  87369. var task = new ImageAssetTask(taskName, url);
  87370. this._tasks.push(task);
  87371. return task;
  87372. };
  87373. /**
  87374. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  87375. * @param taskName defines the name of the new task
  87376. * @param url defines the url of the file to load
  87377. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  87378. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  87379. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  87380. * @returns a new {BABYLON.TextureAssetTask} object
  87381. */
  87382. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  87383. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  87384. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  87385. this._tasks.push(task);
  87386. return task;
  87387. };
  87388. /**
  87389. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  87390. * @param taskName defines the name of the new task
  87391. * @param url defines the url of the file to load
  87392. * @param extensions defines the extension to use to load the cube map (can be null)
  87393. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  87394. * @param files defines the list of files to load (can be null)
  87395. * @returns a new {BABYLON.CubeTextureAssetTask} object
  87396. */
  87397. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  87398. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  87399. this._tasks.push(task);
  87400. return task;
  87401. };
  87402. /**
  87403. *
  87404. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  87405. * @param taskName defines the name of the new task
  87406. * @param url defines the url of the file to load
  87407. * @param size defines the size you want for the cubemap (can be null)
  87408. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  87409. * @param generateHarmonics defines if you want to automatically generate (true by default)
  87410. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  87411. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  87412. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  87413. */
  87414. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  87415. if (noMipmap === void 0) { noMipmap = false; }
  87416. if (generateHarmonics === void 0) { generateHarmonics = true; }
  87417. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  87418. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  87419. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  87420. this._tasks.push(task);
  87421. return task;
  87422. };
  87423. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  87424. var _this = this;
  87425. this._waitingTasksCount--;
  87426. try {
  87427. if (task.taskState === AssetTaskState.DONE) {
  87428. // Let's remove successfull tasks
  87429. BABYLON.Tools.SetImmediate(function () {
  87430. var index = _this._tasks.indexOf(task);
  87431. if (index > -1) {
  87432. _this._tasks.splice(index, 1);
  87433. }
  87434. });
  87435. }
  87436. if (this.onProgress) {
  87437. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  87438. }
  87439. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  87440. }
  87441. catch (e) {
  87442. BABYLON.Tools.Error("Error running progress callbacks.");
  87443. console.log(e);
  87444. }
  87445. if (this._waitingTasksCount === 0) {
  87446. try {
  87447. if (this.onFinish) {
  87448. this.onFinish(this._tasks);
  87449. }
  87450. this.onTasksDoneObservable.notifyObservers(this._tasks);
  87451. }
  87452. catch (e) {
  87453. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  87454. console.log(e);
  87455. }
  87456. this._isLoading = false;
  87457. this._scene.getEngine().hideLoadingUI();
  87458. }
  87459. };
  87460. AssetsManager.prototype._runTask = function (task) {
  87461. var _this = this;
  87462. var done = function () {
  87463. try {
  87464. if (_this.onTaskSuccess) {
  87465. _this.onTaskSuccess(task);
  87466. }
  87467. _this.onTaskSuccessObservable.notifyObservers(task);
  87468. _this._decreaseWaitingTasksCount(task);
  87469. }
  87470. catch (e) {
  87471. error("Error executing task success callbacks", e);
  87472. }
  87473. };
  87474. var error = function (message, exception) {
  87475. task._setErrorObject(message, exception);
  87476. if (_this.onTaskError) {
  87477. _this.onTaskError(task);
  87478. }
  87479. _this.onTaskErrorObservable.notifyObservers(task);
  87480. _this._decreaseWaitingTasksCount(task);
  87481. };
  87482. task.run(this._scene, done, error);
  87483. };
  87484. /**
  87485. * Reset the {BABYLON.AssetsManager} and remove all tasks
  87486. * @return the current instance of the {BABYLON.AssetsManager}
  87487. */
  87488. AssetsManager.prototype.reset = function () {
  87489. this._isLoading = false;
  87490. this._tasks = new Array();
  87491. return this;
  87492. };
  87493. /**
  87494. * Start the loading process
  87495. * @return the current instance of the {BABYLON.AssetsManager}
  87496. */
  87497. AssetsManager.prototype.load = function () {
  87498. if (this._isLoading) {
  87499. return this;
  87500. }
  87501. this._isLoading = true;
  87502. this._waitingTasksCount = this._tasks.length;
  87503. this._totalTasksCount = this._tasks.length;
  87504. if (this._waitingTasksCount === 0) {
  87505. this._isLoading = false;
  87506. if (this.onFinish) {
  87507. this.onFinish(this._tasks);
  87508. }
  87509. this.onTasksDoneObservable.notifyObservers(this._tasks);
  87510. return this;
  87511. }
  87512. if (this.useDefaultLoadingScreen) {
  87513. this._scene.getEngine().displayLoadingUI();
  87514. }
  87515. for (var index = 0; index < this._tasks.length; index++) {
  87516. var task = this._tasks[index];
  87517. this._runTask(task);
  87518. }
  87519. return this;
  87520. };
  87521. return AssetsManager;
  87522. }());
  87523. BABYLON.AssetsManager = AssetsManager;
  87524. })(BABYLON || (BABYLON = {}));
  87525. //# sourceMappingURL=babylon.assetsManager.js.map
  87526. "use strict";
  87527. var BABYLON;
  87528. (function (BABYLON) {
  87529. var serializedGeometries = [];
  87530. var serializeGeometry = function (geometry, serializationGeometries) {
  87531. if (serializedGeometries[geometry.id]) {
  87532. return;
  87533. }
  87534. if (geometry.doNotSerialize) {
  87535. return;
  87536. }
  87537. if (geometry instanceof BABYLON.BoxGeometry) {
  87538. serializationGeometries.boxes.push(geometry.serialize());
  87539. }
  87540. else if (geometry instanceof BABYLON.SphereGeometry) {
  87541. serializationGeometries.spheres.push(geometry.serialize());
  87542. }
  87543. else if (geometry instanceof BABYLON.CylinderGeometry) {
  87544. serializationGeometries.cylinders.push(geometry.serialize());
  87545. }
  87546. else if (geometry instanceof BABYLON.TorusGeometry) {
  87547. serializationGeometries.toruses.push(geometry.serialize());
  87548. }
  87549. else if (geometry instanceof BABYLON.GroundGeometry) {
  87550. serializationGeometries.grounds.push(geometry.serialize());
  87551. }
  87552. else if (geometry instanceof BABYLON.Plane) {
  87553. serializationGeometries.planes.push(geometry.serialize());
  87554. }
  87555. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  87556. serializationGeometries.torusKnots.push(geometry.serialize());
  87557. }
  87558. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  87559. throw new Error("Unknown primitive type");
  87560. }
  87561. else {
  87562. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  87563. }
  87564. serializedGeometries[geometry.id] = true;
  87565. };
  87566. var serializeMesh = function (mesh, serializationScene) {
  87567. var serializationObject = {};
  87568. // Geometry
  87569. var geometry = mesh._geometry;
  87570. if (geometry) {
  87571. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  87572. // 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
  87573. serializeGeometry(geometry, serializationScene.geometries);
  87574. }
  87575. }
  87576. // Custom
  87577. if (mesh.serialize) {
  87578. mesh.serialize(serializationObject);
  87579. }
  87580. return serializationObject;
  87581. };
  87582. var finalizeSingleMesh = function (mesh, serializationObject) {
  87583. //only works if the mesh is already loaded
  87584. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  87585. //serialize material
  87586. if (mesh.material) {
  87587. if (mesh.material instanceof BABYLON.StandardMaterial) {
  87588. serializationObject.materials = serializationObject.materials || [];
  87589. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  87590. serializationObject.materials.push(mesh.material.serialize());
  87591. }
  87592. }
  87593. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  87594. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  87595. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  87596. serializationObject.multiMaterials.push(mesh.material.serialize());
  87597. }
  87598. }
  87599. }
  87600. //serialize geometry
  87601. var geometry = mesh._geometry;
  87602. if (geometry) {
  87603. if (!serializationObject.geometries) {
  87604. serializationObject.geometries = {};
  87605. serializationObject.geometries.boxes = [];
  87606. serializationObject.geometries.spheres = [];
  87607. serializationObject.geometries.cylinders = [];
  87608. serializationObject.geometries.toruses = [];
  87609. serializationObject.geometries.grounds = [];
  87610. serializationObject.geometries.planes = [];
  87611. serializationObject.geometries.torusKnots = [];
  87612. serializationObject.geometries.vertexData = [];
  87613. }
  87614. serializeGeometry(geometry, serializationObject.geometries);
  87615. }
  87616. // Skeletons
  87617. if (mesh.skeleton) {
  87618. serializationObject.skeletons = serializationObject.skeletons || [];
  87619. serializationObject.skeletons.push(mesh.skeleton.serialize());
  87620. }
  87621. //serialize the actual mesh
  87622. serializationObject.meshes = serializationObject.meshes || [];
  87623. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  87624. }
  87625. };
  87626. var SceneSerializer = /** @class */ (function () {
  87627. function SceneSerializer() {
  87628. }
  87629. SceneSerializer.ClearCache = function () {
  87630. serializedGeometries = [];
  87631. };
  87632. SceneSerializer.Serialize = function (scene) {
  87633. var serializationObject = {};
  87634. SceneSerializer.ClearCache();
  87635. // Scene
  87636. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  87637. serializationObject.autoClear = scene.autoClear;
  87638. serializationObject.clearColor = scene.clearColor.asArray();
  87639. serializationObject.ambientColor = scene.ambientColor.asArray();
  87640. serializationObject.gravity = scene.gravity.asArray();
  87641. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  87642. serializationObject.workerCollisions = scene.workerCollisions;
  87643. // Fog
  87644. if (scene.fogMode && scene.fogMode !== 0) {
  87645. serializationObject.fogMode = scene.fogMode;
  87646. serializationObject.fogColor = scene.fogColor.asArray();
  87647. serializationObject.fogStart = scene.fogStart;
  87648. serializationObject.fogEnd = scene.fogEnd;
  87649. serializationObject.fogDensity = scene.fogDensity;
  87650. }
  87651. //Physics
  87652. if (scene.isPhysicsEnabled()) {
  87653. var physicEngine = scene.getPhysicsEngine();
  87654. if (physicEngine) {
  87655. serializationObject.physicsEnabled = true;
  87656. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  87657. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  87658. }
  87659. }
  87660. // Metadata
  87661. if (scene.metadata) {
  87662. serializationObject.metadata = scene.metadata;
  87663. }
  87664. // Morph targets
  87665. serializationObject.morphTargetManagers = [];
  87666. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  87667. var abstractMesh = _a[_i];
  87668. var manager = abstractMesh.morphTargetManager;
  87669. if (manager) {
  87670. serializationObject.morphTargetManagers.push(manager.serialize());
  87671. }
  87672. }
  87673. // Lights
  87674. serializationObject.lights = [];
  87675. var index;
  87676. var light;
  87677. for (index = 0; index < scene.lights.length; index++) {
  87678. light = scene.lights[index];
  87679. if (!light.doNotSerialize) {
  87680. serializationObject.lights.push(light.serialize());
  87681. }
  87682. }
  87683. // Cameras
  87684. serializationObject.cameras = [];
  87685. for (index = 0; index < scene.cameras.length; index++) {
  87686. var camera = scene.cameras[index];
  87687. if (!camera.doNotSerialize) {
  87688. serializationObject.cameras.push(camera.serialize());
  87689. }
  87690. }
  87691. if (scene.activeCamera) {
  87692. serializationObject.activeCameraID = scene.activeCamera.id;
  87693. }
  87694. // Animations
  87695. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  87696. // Materials
  87697. serializationObject.materials = [];
  87698. serializationObject.multiMaterials = [];
  87699. var material;
  87700. for (index = 0; index < scene.materials.length; index++) {
  87701. material = scene.materials[index];
  87702. if (!material.doNotSerialize) {
  87703. serializationObject.materials.push(material.serialize());
  87704. }
  87705. }
  87706. // MultiMaterials
  87707. serializationObject.multiMaterials = [];
  87708. for (index = 0; index < scene.multiMaterials.length; index++) {
  87709. var multiMaterial = scene.multiMaterials[index];
  87710. serializationObject.multiMaterials.push(multiMaterial.serialize());
  87711. }
  87712. // Environment texture
  87713. if (scene.environmentTexture) {
  87714. serializationObject.environmentTexture = scene.environmentTexture.name;
  87715. }
  87716. // Skeletons
  87717. serializationObject.skeletons = [];
  87718. for (index = 0; index < scene.skeletons.length; index++) {
  87719. var skeleton = scene.skeletons[index];
  87720. if (!skeleton.doNotSerialize) {
  87721. serializationObject.skeletons.push(skeleton.serialize());
  87722. }
  87723. }
  87724. // Transform nodes
  87725. serializationObject.transformNodes = [];
  87726. for (index = 0; index < scene.transformNodes.length; index++) {
  87727. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  87728. }
  87729. // Geometries
  87730. serializationObject.geometries = {};
  87731. serializationObject.geometries.boxes = [];
  87732. serializationObject.geometries.spheres = [];
  87733. serializationObject.geometries.cylinders = [];
  87734. serializationObject.geometries.toruses = [];
  87735. serializationObject.geometries.grounds = [];
  87736. serializationObject.geometries.planes = [];
  87737. serializationObject.geometries.torusKnots = [];
  87738. serializationObject.geometries.vertexData = [];
  87739. serializedGeometries = [];
  87740. var geometries = scene.getGeometries();
  87741. for (index = 0; index < geometries.length; index++) {
  87742. var geometry = geometries[index];
  87743. if (geometry.isReady()) {
  87744. serializeGeometry(geometry, serializationObject.geometries);
  87745. }
  87746. }
  87747. // Meshes
  87748. serializationObject.meshes = [];
  87749. for (index = 0; index < scene.meshes.length; index++) {
  87750. var abstractMesh = scene.meshes[index];
  87751. if (abstractMesh instanceof BABYLON.Mesh) {
  87752. var mesh = abstractMesh;
  87753. if (!mesh.doNotSerialize) {
  87754. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  87755. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  87756. }
  87757. }
  87758. }
  87759. }
  87760. // Particles Systems
  87761. serializationObject.particleSystems = [];
  87762. for (index = 0; index < scene.particleSystems.length; index++) {
  87763. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  87764. }
  87765. // Lens flares
  87766. serializationObject.lensFlareSystems = [];
  87767. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  87768. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  87769. }
  87770. // Shadows
  87771. serializationObject.shadowGenerators = [];
  87772. for (index = 0; index < scene.lights.length; index++) {
  87773. light = scene.lights[index];
  87774. var shadowGenerator = light.getShadowGenerator();
  87775. if (shadowGenerator) {
  87776. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  87777. }
  87778. }
  87779. // Action Manager
  87780. if (scene.actionManager) {
  87781. serializationObject.actions = scene.actionManager.serialize("scene");
  87782. }
  87783. // Audio
  87784. serializationObject.sounds = [];
  87785. for (index = 0; index < scene.soundTracks.length; index++) {
  87786. var soundtrack = scene.soundTracks[index];
  87787. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  87788. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  87789. }
  87790. }
  87791. return serializationObject;
  87792. };
  87793. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  87794. if (withParents === void 0) { withParents = false; }
  87795. if (withChildren === void 0) { withChildren = false; }
  87796. var serializationObject = {};
  87797. SceneSerializer.ClearCache();
  87798. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  87799. if (withParents || withChildren) {
  87800. //deliberate for loop! not for each, appended should be processed as well.
  87801. for (var i = 0; i < toSerialize.length; ++i) {
  87802. if (withChildren) {
  87803. toSerialize[i].getDescendants().forEach(function (node) {
  87804. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  87805. toSerialize.push(node);
  87806. }
  87807. });
  87808. }
  87809. //make sure the array doesn't contain the object already
  87810. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  87811. toSerialize.push(toSerialize[i].parent);
  87812. }
  87813. }
  87814. }
  87815. toSerialize.forEach(function (mesh) {
  87816. finalizeSingleMesh(mesh, serializationObject);
  87817. });
  87818. return serializationObject;
  87819. };
  87820. return SceneSerializer;
  87821. }());
  87822. BABYLON.SceneSerializer = SceneSerializer;
  87823. })(BABYLON || (BABYLON = {}));
  87824. //# sourceMappingURL=babylon.sceneSerializer.js.map
  87825. "use strict";
  87826. var BABYLON;
  87827. (function (BABYLON) {
  87828. var ReflectionProbe = /** @class */ (function () {
  87829. function ReflectionProbe(name, size, scene, generateMipMaps) {
  87830. if (generateMipMaps === void 0) { generateMipMaps = true; }
  87831. var _this = this;
  87832. this.name = name;
  87833. this._viewMatrix = BABYLON.Matrix.Identity();
  87834. this._target = BABYLON.Vector3.Zero();
  87835. this._add = BABYLON.Vector3.Zero();
  87836. this._invertYAxis = false;
  87837. this.position = BABYLON.Vector3.Zero();
  87838. this._scene = scene;
  87839. this._scene.reflectionProbes.push(this);
  87840. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  87841. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  87842. switch (faceIndex) {
  87843. case 0:
  87844. _this._add.copyFromFloats(1, 0, 0);
  87845. break;
  87846. case 1:
  87847. _this._add.copyFromFloats(-1, 0, 0);
  87848. break;
  87849. case 2:
  87850. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  87851. break;
  87852. case 3:
  87853. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  87854. break;
  87855. case 4:
  87856. _this._add.copyFromFloats(0, 0, 1);
  87857. break;
  87858. case 5:
  87859. _this._add.copyFromFloats(0, 0, -1);
  87860. break;
  87861. }
  87862. if (_this._attachedMesh) {
  87863. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  87864. }
  87865. _this.position.addToRef(_this._add, _this._target);
  87866. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  87867. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  87868. scene._forcedViewPosition = _this.position;
  87869. });
  87870. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  87871. scene._forcedViewPosition = null;
  87872. scene.updateTransformMatrix(true);
  87873. });
  87874. if (scene.activeCamera) {
  87875. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  87876. }
  87877. }
  87878. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  87879. get: function () {
  87880. return this._renderTargetTexture.samples;
  87881. },
  87882. set: function (value) {
  87883. this._renderTargetTexture.samples = value;
  87884. },
  87885. enumerable: true,
  87886. configurable: true
  87887. });
  87888. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  87889. get: function () {
  87890. return this._renderTargetTexture.refreshRate;
  87891. },
  87892. set: function (value) {
  87893. this._renderTargetTexture.refreshRate = value;
  87894. },
  87895. enumerable: true,
  87896. configurable: true
  87897. });
  87898. ReflectionProbe.prototype.getScene = function () {
  87899. return this._scene;
  87900. };
  87901. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  87902. get: function () {
  87903. return this._renderTargetTexture;
  87904. },
  87905. enumerable: true,
  87906. configurable: true
  87907. });
  87908. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  87909. get: function () {
  87910. return this._renderTargetTexture.renderList;
  87911. },
  87912. enumerable: true,
  87913. configurable: true
  87914. });
  87915. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  87916. this._attachedMesh = mesh;
  87917. };
  87918. /**
  87919. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  87920. *
  87921. * @param renderingGroupId The rendering group id corresponding to its index
  87922. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  87923. */
  87924. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  87925. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  87926. };
  87927. ReflectionProbe.prototype.dispose = function () {
  87928. var index = this._scene.reflectionProbes.indexOf(this);
  87929. if (index !== -1) {
  87930. // Remove from the scene if found
  87931. this._scene.reflectionProbes.splice(index, 1);
  87932. }
  87933. if (this._renderTargetTexture) {
  87934. this._renderTargetTexture.dispose();
  87935. this._renderTargetTexture = null;
  87936. }
  87937. };
  87938. return ReflectionProbe;
  87939. }());
  87940. BABYLON.ReflectionProbe = ReflectionProbe;
  87941. })(BABYLON || (BABYLON = {}));
  87942. //# sourceMappingURL=babylon.reflectionProbe.js.map
  87943. "use strict";
  87944. var BABYLON;
  87945. (function (BABYLON) {
  87946. var Layer = /** @class */ (function () {
  87947. function Layer(name, imgUrl, scene, isBackground, color) {
  87948. this.name = name;
  87949. this.scale = new BABYLON.Vector2(1, 1);
  87950. this.offset = new BABYLON.Vector2(0, 0);
  87951. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  87952. this.layerMask = 0x0FFFFFFF;
  87953. this._vertexBuffers = {};
  87954. // Events
  87955. /**
  87956. * An event triggered when the layer is disposed.
  87957. * @type {BABYLON.Observable}
  87958. */
  87959. this.onDisposeObservable = new BABYLON.Observable();
  87960. /**
  87961. * An event triggered before rendering the scene
  87962. * @type {BABYLON.Observable}
  87963. */
  87964. this.onBeforeRenderObservable = new BABYLON.Observable();
  87965. /**
  87966. * An event triggered after rendering the scene
  87967. * @type {BABYLON.Observable}
  87968. */
  87969. this.onAfterRenderObservable = new BABYLON.Observable();
  87970. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  87971. this.isBackground = isBackground === undefined ? true : isBackground;
  87972. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  87973. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  87974. this._scene.layers.push(this);
  87975. var engine = this._scene.getEngine();
  87976. // VBO
  87977. var vertices = [];
  87978. vertices.push(1, 1);
  87979. vertices.push(-1, 1);
  87980. vertices.push(-1, -1);
  87981. vertices.push(1, -1);
  87982. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  87983. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  87984. this._createIndexBuffer();
  87985. // Effects
  87986. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  87987. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  87988. }
  87989. Object.defineProperty(Layer.prototype, "onDispose", {
  87990. set: function (callback) {
  87991. if (this._onDisposeObserver) {
  87992. this.onDisposeObservable.remove(this._onDisposeObserver);
  87993. }
  87994. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  87995. },
  87996. enumerable: true,
  87997. configurable: true
  87998. });
  87999. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  88000. set: function (callback) {
  88001. if (this._onBeforeRenderObserver) {
  88002. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  88003. }
  88004. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  88005. },
  88006. enumerable: true,
  88007. configurable: true
  88008. });
  88009. Object.defineProperty(Layer.prototype, "onAfterRender", {
  88010. set: function (callback) {
  88011. if (this._onAfterRenderObserver) {
  88012. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  88013. }
  88014. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  88015. },
  88016. enumerable: true,
  88017. configurable: true
  88018. });
  88019. Layer.prototype._createIndexBuffer = function () {
  88020. var engine = this._scene.getEngine();
  88021. // Indices
  88022. var indices = [];
  88023. indices.push(0);
  88024. indices.push(1);
  88025. indices.push(2);
  88026. indices.push(0);
  88027. indices.push(2);
  88028. indices.push(3);
  88029. this._indexBuffer = engine.createIndexBuffer(indices);
  88030. };
  88031. Layer.prototype._rebuild = function () {
  88032. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88033. if (vb) {
  88034. vb._rebuild();
  88035. }
  88036. this._createIndexBuffer();
  88037. };
  88038. Layer.prototype.render = function () {
  88039. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  88040. // Check
  88041. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  88042. return;
  88043. var engine = this._scene.getEngine();
  88044. this.onBeforeRenderObservable.notifyObservers(this);
  88045. // Render
  88046. engine.enableEffect(currentEffect);
  88047. engine.setState(false);
  88048. // Texture
  88049. currentEffect.setTexture("textureSampler", this.texture);
  88050. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  88051. // Color
  88052. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  88053. // Scale / offset
  88054. currentEffect.setVector2("offset", this.offset);
  88055. currentEffect.setVector2("scale", this.scale);
  88056. // VBOs
  88057. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  88058. // Draw order
  88059. if (!this.alphaTest) {
  88060. engine.setAlphaMode(this.alphaBlendingMode);
  88061. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  88062. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  88063. }
  88064. else {
  88065. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  88066. }
  88067. this.onAfterRenderObservable.notifyObservers(this);
  88068. };
  88069. Layer.prototype.dispose = function () {
  88070. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88071. if (vertexBuffer) {
  88072. vertexBuffer.dispose();
  88073. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  88074. }
  88075. if (this._indexBuffer) {
  88076. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  88077. this._indexBuffer = null;
  88078. }
  88079. if (this.texture) {
  88080. this.texture.dispose();
  88081. this.texture = null;
  88082. }
  88083. // Remove from scene
  88084. var index = this._scene.layers.indexOf(this);
  88085. this._scene.layers.splice(index, 1);
  88086. // Callback
  88087. this.onDisposeObservable.notifyObservers(this);
  88088. this.onDisposeObservable.clear();
  88089. this.onAfterRenderObservable.clear();
  88090. this.onBeforeRenderObservable.clear();
  88091. };
  88092. return Layer;
  88093. }());
  88094. BABYLON.Layer = Layer;
  88095. })(BABYLON || (BABYLON = {}));
  88096. //# sourceMappingURL=babylon.layer.js.map
  88097. "use strict";
  88098. var BABYLON;
  88099. (function (BABYLON) {
  88100. var TextureTools = /** @class */ (function () {
  88101. function TextureTools() {
  88102. }
  88103. /**
  88104. * Uses the GPU to create a copy texture rescaled at a given size
  88105. * @param texture Texture to copy from
  88106. * @param width Desired width
  88107. * @param height Desired height
  88108. * @return Generated texture
  88109. */
  88110. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  88111. if (useBilinearMode === void 0) { useBilinearMode = true; }
  88112. var scene = texture.getScene();
  88113. var engine = scene.getEngine();
  88114. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  88115. rtt.wrapU = texture.wrapU;
  88116. rtt.wrapV = texture.wrapV;
  88117. rtt.uOffset = texture.uOffset;
  88118. rtt.vOffset = texture.vOffset;
  88119. rtt.uScale = texture.uScale;
  88120. rtt.vScale = texture.vScale;
  88121. rtt.uAng = texture.uAng;
  88122. rtt.vAng = texture.vAng;
  88123. rtt.wAng = texture.wAng;
  88124. rtt.coordinatesIndex = texture.coordinatesIndex;
  88125. rtt.level = texture.level;
  88126. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  88127. rtt._texture.isReady = false;
  88128. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88129. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88130. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  88131. passPostProcess.getEffect().executeWhenCompiled(function () {
  88132. passPostProcess.onApply = function (effect) {
  88133. effect.setTexture("textureSampler", texture);
  88134. };
  88135. var internalTexture = rtt.getInternalTexture();
  88136. if (internalTexture) {
  88137. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  88138. engine.unBindFramebuffer(internalTexture);
  88139. rtt.disposeFramebufferObjects();
  88140. passPostProcess.dispose();
  88141. internalTexture.isReady = true;
  88142. }
  88143. });
  88144. return rtt;
  88145. };
  88146. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  88147. if (!scene._environmentBRDFTexture) {
  88148. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  88149. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88150. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88151. scene._environmentBRDFTexture = texture;
  88152. }
  88153. return scene._environmentBRDFTexture;
  88154. };
  88155. 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=";
  88156. return TextureTools;
  88157. }());
  88158. BABYLON.TextureTools = TextureTools;
  88159. })(BABYLON || (BABYLON = {}));
  88160. //# sourceMappingURL=babylon.textureTools.js.map
  88161. "use strict";
  88162. var BABYLON;
  88163. (function (BABYLON) {
  88164. var FramingBehavior = /** @class */ (function () {
  88165. function FramingBehavior() {
  88166. this._mode = FramingBehavior.FitFrustumSidesMode;
  88167. this._radiusScale = 1.0;
  88168. this._positionScale = 0.5;
  88169. this._defaultElevation = 0.3;
  88170. this._elevationReturnTime = 1500;
  88171. this._elevationReturnWaitTime = 1000;
  88172. this._zoomStopsAnimation = false;
  88173. this._framingTime = 1500;
  88174. this._isPointerDown = false;
  88175. this._lastInteractionTime = -Infinity;
  88176. // Framing control
  88177. this._animatables = new Array();
  88178. this._betaIsAnimating = false;
  88179. }
  88180. Object.defineProperty(FramingBehavior.prototype, "name", {
  88181. get: function () {
  88182. return "Framing";
  88183. },
  88184. enumerable: true,
  88185. configurable: true
  88186. });
  88187. Object.defineProperty(FramingBehavior.prototype, "mode", {
  88188. /**
  88189. * Gets current mode used by the behavior.
  88190. */
  88191. get: function () {
  88192. return this._mode;
  88193. },
  88194. /**
  88195. * Sets the current mode used by the behavior
  88196. */
  88197. set: function (mode) {
  88198. this._mode = mode;
  88199. },
  88200. enumerable: true,
  88201. configurable: true
  88202. });
  88203. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  88204. /**
  88205. * Gets the scale applied to the radius
  88206. */
  88207. get: function () {
  88208. return this._radiusScale;
  88209. },
  88210. /**
  88211. * Sets the scale applied to the radius (1 by default)
  88212. */
  88213. set: function (radius) {
  88214. this._radiusScale = radius;
  88215. },
  88216. enumerable: true,
  88217. configurable: true
  88218. });
  88219. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  88220. /**
  88221. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  88222. */
  88223. get: function () {
  88224. return this._positionScale;
  88225. },
  88226. /**
  88227. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  88228. */
  88229. set: function (scale) {
  88230. this._positionScale = scale;
  88231. },
  88232. enumerable: true,
  88233. configurable: true
  88234. });
  88235. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  88236. /**
  88237. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  88238. * behaviour is triggered, in radians.
  88239. */
  88240. get: function () {
  88241. return this._defaultElevation;
  88242. },
  88243. /**
  88244. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  88245. * behaviour is triggered, in radians.
  88246. */
  88247. set: function (elevation) {
  88248. this._defaultElevation = elevation;
  88249. },
  88250. enumerable: true,
  88251. configurable: true
  88252. });
  88253. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  88254. /**
  88255. * Gets the time (in milliseconds) taken to return to the default beta position.
  88256. * Negative value indicates camera should not return to default.
  88257. */
  88258. get: function () {
  88259. return this._elevationReturnTime;
  88260. },
  88261. /**
  88262. * Sets the time (in milliseconds) taken to return to the default beta position.
  88263. * Negative value indicates camera should not return to default.
  88264. */
  88265. set: function (speed) {
  88266. this._elevationReturnTime = speed;
  88267. },
  88268. enumerable: true,
  88269. configurable: true
  88270. });
  88271. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  88272. /**
  88273. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  88274. */
  88275. get: function () {
  88276. return this._elevationReturnWaitTime;
  88277. },
  88278. /**
  88279. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  88280. */
  88281. set: function (time) {
  88282. this._elevationReturnWaitTime = time;
  88283. },
  88284. enumerable: true,
  88285. configurable: true
  88286. });
  88287. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  88288. /**
  88289. * Gets the flag that indicates if user zooming should stop animation.
  88290. */
  88291. get: function () {
  88292. return this._zoomStopsAnimation;
  88293. },
  88294. /**
  88295. * Sets the flag that indicates if user zooming should stop animation.
  88296. */
  88297. set: function (flag) {
  88298. this._zoomStopsAnimation = flag;
  88299. },
  88300. enumerable: true,
  88301. configurable: true
  88302. });
  88303. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  88304. /**
  88305. * Gets the transition time when framing the mesh, in milliseconds
  88306. */
  88307. get: function () {
  88308. return this._framingTime;
  88309. },
  88310. /**
  88311. * Sets the transition time when framing the mesh, in milliseconds
  88312. */
  88313. set: function (time) {
  88314. this._framingTime = time;
  88315. },
  88316. enumerable: true,
  88317. configurable: true
  88318. });
  88319. FramingBehavior.prototype.init = function () {
  88320. // Do notihng
  88321. };
  88322. FramingBehavior.prototype.attach = function (camera) {
  88323. var _this = this;
  88324. this._attachedCamera = camera;
  88325. var scene = this._attachedCamera.getScene();
  88326. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  88327. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  88328. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88329. _this._isPointerDown = true;
  88330. return;
  88331. }
  88332. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  88333. _this._isPointerDown = false;
  88334. }
  88335. });
  88336. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  88337. if (mesh) {
  88338. _this.zoomOnMesh(mesh);
  88339. }
  88340. });
  88341. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  88342. // Stop the animation if there is user interaction and the animation should stop for this interaction
  88343. _this._applyUserInteraction();
  88344. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  88345. // back to the default position after a given timeout
  88346. _this._maintainCameraAboveGround();
  88347. });
  88348. };
  88349. FramingBehavior.prototype.detach = function () {
  88350. if (!this._attachedCamera) {
  88351. return;
  88352. }
  88353. var scene = this._attachedCamera.getScene();
  88354. if (this._onPrePointerObservableObserver) {
  88355. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  88356. }
  88357. if (this._onAfterCheckInputsObserver) {
  88358. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  88359. }
  88360. if (this._onMeshTargetChangedObserver) {
  88361. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  88362. }
  88363. this._attachedCamera = null;
  88364. };
  88365. /**
  88366. * Targets the given mesh and updates zoom level accordingly.
  88367. * @param mesh The mesh to target.
  88368. * @param radius Optional. If a cached radius position already exists, overrides default.
  88369. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88370. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88371. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88372. */
  88373. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  88374. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88375. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88376. mesh.computeWorldMatrix(true);
  88377. var boundingBox = mesh.getBoundingInfo().boundingBox;
  88378. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  88379. };
  88380. /**
  88381. * Targets the given mesh with its children and updates zoom level accordingly.
  88382. * @param mesh The mesh to target.
  88383. * @param radius Optional. If a cached radius position already exists, overrides default.
  88384. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88385. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88386. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88387. */
  88388. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  88389. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88390. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88391. mesh.computeWorldMatrix(true);
  88392. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  88393. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  88394. };
  88395. /**
  88396. * Targets the given meshes with their children and updates zoom level accordingly.
  88397. * @param meshes The mesh to target.
  88398. * @param radius Optional. If a cached radius position already exists, overrides default.
  88399. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88400. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88401. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88402. */
  88403. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  88404. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88405. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88406. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  88407. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  88408. for (var i = 0; i < meshes.length; i++) {
  88409. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  88410. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  88411. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  88412. }
  88413. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  88414. };
  88415. /**
  88416. * Targets the given mesh and updates zoom level accordingly.
  88417. * @param mesh The mesh to target.
  88418. * @param radius Optional. If a cached radius position already exists, overrides default.
  88419. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88420. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88421. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88422. */
  88423. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  88424. var _this = this;
  88425. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88426. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88427. var zoomTarget;
  88428. if (!this._attachedCamera) {
  88429. return;
  88430. }
  88431. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  88432. var bottom = minimumWorld.y;
  88433. var top = maximumWorld.y;
  88434. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  88435. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  88436. if (focusOnOriginXZ) {
  88437. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  88438. }
  88439. else {
  88440. var centerWorld = minimumWorld.add(radiusWorld);
  88441. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  88442. }
  88443. if (!this._vectorTransition) {
  88444. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  88445. }
  88446. this._betaIsAnimating = true;
  88447. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  88448. if (animatable) {
  88449. this._animatables.push(animatable);
  88450. }
  88451. // sets the radius and lower radius bounds
  88452. // Small delta ensures camera is not always at lower zoom limit.
  88453. var radius = 0;
  88454. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  88455. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  88456. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  88457. radius = position;
  88458. }
  88459. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  88460. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  88461. if (this._attachedCamera.lowerRadiusLimit === null) {
  88462. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  88463. }
  88464. }
  88465. // Set sensibilities
  88466. var extend = maximumWorld.subtract(minimumWorld).length();
  88467. this._attachedCamera.panningSensibility = 5000 / extend;
  88468. this._attachedCamera.wheelPrecision = 100 / radius;
  88469. // transition to new radius
  88470. if (!this._radiusTransition) {
  88471. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  88472. }
  88473. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  88474. _this.stopAllAnimations();
  88475. if (onAnimationEnd) {
  88476. onAnimationEnd();
  88477. }
  88478. if (_this._attachedCamera) {
  88479. _this._attachedCamera.storeState();
  88480. }
  88481. });
  88482. if (animatable) {
  88483. this._animatables.push(animatable);
  88484. }
  88485. };
  88486. /**
  88487. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  88488. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  88489. * frustum width.
  88490. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  88491. * to fully enclose the mesh in the viewing frustum.
  88492. */
  88493. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  88494. var size = maximumWorld.subtract(minimumWorld);
  88495. var boxVectorGlobalDiagonal = size.length();
  88496. var frustumSlope = this._getFrustumSlope();
  88497. // Formula for setting distance
  88498. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  88499. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  88500. // Horizon distance
  88501. var radius = radiusWithoutFraming * this._radiusScale;
  88502. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  88503. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  88504. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  88505. var camera = this._attachedCamera;
  88506. if (!camera) {
  88507. return 0;
  88508. }
  88509. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  88510. // Don't exceed the requested limit
  88511. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  88512. }
  88513. // Don't exceed the upper radius limit
  88514. if (camera.upperRadiusLimit) {
  88515. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  88516. }
  88517. return distance;
  88518. };
  88519. /**
  88520. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  88521. * is automatically returned to its default position (expected to be above ground plane).
  88522. */
  88523. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  88524. var _this = this;
  88525. if (this._elevationReturnTime < 0) {
  88526. return;
  88527. }
  88528. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  88529. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  88530. var limitBeta = Math.PI * 0.5;
  88531. // Bring the camera back up if below the ground plane
  88532. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  88533. this._betaIsAnimating = true;
  88534. //Transition to new position
  88535. this.stopAllAnimations();
  88536. if (!this._betaTransition) {
  88537. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  88538. }
  88539. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  88540. _this._clearAnimationLocks();
  88541. _this.stopAllAnimations();
  88542. });
  88543. if (animatabe) {
  88544. this._animatables.push(animatabe);
  88545. }
  88546. }
  88547. };
  88548. /**
  88549. * Returns the frustum slope based on the canvas ratio and camera FOV
  88550. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  88551. */
  88552. FramingBehavior.prototype._getFrustumSlope = function () {
  88553. // Calculate the viewport ratio
  88554. // Aspect Ratio is Height/Width.
  88555. var camera = this._attachedCamera;
  88556. if (!camera) {
  88557. return BABYLON.Vector2.Zero();
  88558. }
  88559. var engine = camera.getScene().getEngine();
  88560. var aspectRatio = engine.getAspectRatio(camera);
  88561. // Camera FOV is the vertical field of view (top-bottom) in radians.
  88562. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  88563. var frustumSlopeY = Math.tan(camera.fov / 2);
  88564. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  88565. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  88566. // along the forward vector.
  88567. var frustumSlopeX = frustumSlopeY * aspectRatio;
  88568. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  88569. };
  88570. /**
  88571. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  88572. */
  88573. FramingBehavior.prototype._clearAnimationLocks = function () {
  88574. this._betaIsAnimating = false;
  88575. };
  88576. /**
  88577. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  88578. */
  88579. FramingBehavior.prototype._applyUserInteraction = function () {
  88580. if (this.isUserIsMoving) {
  88581. this._lastInteractionTime = BABYLON.Tools.Now;
  88582. this.stopAllAnimations();
  88583. this._clearAnimationLocks();
  88584. }
  88585. };
  88586. /**
  88587. * Stops and removes all animations that have been applied to the camera
  88588. */
  88589. FramingBehavior.prototype.stopAllAnimations = function () {
  88590. if (this._attachedCamera) {
  88591. this._attachedCamera.animations = [];
  88592. }
  88593. while (this._animatables.length) {
  88594. if (this._animatables[0]) {
  88595. this._animatables[0].onAnimationEnd = null;
  88596. this._animatables[0].stop();
  88597. }
  88598. this._animatables.shift();
  88599. }
  88600. };
  88601. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  88602. /**
  88603. * Gets a value indicating if the user is moving the camera
  88604. */
  88605. get: function () {
  88606. if (!this._attachedCamera) {
  88607. return false;
  88608. }
  88609. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  88610. this._attachedCamera.inertialBetaOffset !== 0 ||
  88611. this._attachedCamera.inertialRadiusOffset !== 0 ||
  88612. this._attachedCamera.inertialPanningX !== 0 ||
  88613. this._attachedCamera.inertialPanningY !== 0 ||
  88614. this._isPointerDown;
  88615. },
  88616. enumerable: true,
  88617. configurable: true
  88618. });
  88619. /**
  88620. * The easing function used by animations
  88621. */
  88622. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  88623. /**
  88624. * The easing mode used by animations
  88625. */
  88626. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  88627. // Statics
  88628. /**
  88629. * The camera can move all the way towards the mesh.
  88630. */
  88631. FramingBehavior.IgnoreBoundsSizeMode = 0;
  88632. /**
  88633. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  88634. */
  88635. FramingBehavior.FitFrustumSidesMode = 1;
  88636. return FramingBehavior;
  88637. }());
  88638. BABYLON.FramingBehavior = FramingBehavior;
  88639. })(BABYLON || (BABYLON = {}));
  88640. //# sourceMappingURL=babylon.framingBehavior.js.map
  88641. "use strict";
  88642. var BABYLON;
  88643. (function (BABYLON) {
  88644. /**
  88645. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  88646. */
  88647. var BouncingBehavior = /** @class */ (function () {
  88648. function BouncingBehavior() {
  88649. /**
  88650. * The duration of the animation, in milliseconds
  88651. */
  88652. this.transitionDuration = 450;
  88653. /**
  88654. * Length of the distance animated by the transition when lower radius is reached
  88655. */
  88656. this.lowerRadiusTransitionRange = 2;
  88657. /**
  88658. * Length of the distance animated by the transition when upper radius is reached
  88659. */
  88660. this.upperRadiusTransitionRange = -2;
  88661. this._autoTransitionRange = false;
  88662. // Animations
  88663. this._radiusIsAnimating = false;
  88664. this._radiusBounceTransition = null;
  88665. this._animatables = new Array();
  88666. }
  88667. Object.defineProperty(BouncingBehavior.prototype, "name", {
  88668. get: function () {
  88669. return "Bouncing";
  88670. },
  88671. enumerable: true,
  88672. configurable: true
  88673. });
  88674. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  88675. /**
  88676. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  88677. */
  88678. get: function () {
  88679. return this._autoTransitionRange;
  88680. },
  88681. /**
  88682. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  88683. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  88684. */
  88685. set: function (value) {
  88686. var _this = this;
  88687. if (this._autoTransitionRange === value) {
  88688. return;
  88689. }
  88690. this._autoTransitionRange = value;
  88691. var camera = this._attachedCamera;
  88692. if (!camera) {
  88693. return;
  88694. }
  88695. if (value) {
  88696. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  88697. if (!mesh) {
  88698. return;
  88699. }
  88700. mesh.computeWorldMatrix(true);
  88701. var diagonal = mesh.getBoundingInfo().diagonalLength;
  88702. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  88703. _this.upperRadiusTransitionRange = diagonal * 0.05;
  88704. });
  88705. }
  88706. else if (this._onMeshTargetChangedObserver) {
  88707. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  88708. }
  88709. },
  88710. enumerable: true,
  88711. configurable: true
  88712. });
  88713. BouncingBehavior.prototype.init = function () {
  88714. // Do notihng
  88715. };
  88716. BouncingBehavior.prototype.attach = function (camera) {
  88717. var _this = this;
  88718. this._attachedCamera = camera;
  88719. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  88720. if (!_this._attachedCamera) {
  88721. return;
  88722. }
  88723. // Add the bounce animation to the lower radius limit
  88724. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  88725. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  88726. }
  88727. // Add the bounce animation to the upper radius limit
  88728. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  88729. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  88730. }
  88731. });
  88732. };
  88733. BouncingBehavior.prototype.detach = function () {
  88734. if (!this._attachedCamera) {
  88735. return;
  88736. }
  88737. if (this._onAfterCheckInputsObserver) {
  88738. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  88739. }
  88740. if (this._onMeshTargetChangedObserver) {
  88741. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  88742. }
  88743. this._attachedCamera = null;
  88744. };
  88745. /**
  88746. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  88747. * @param radiusLimit The limit to check against.
  88748. * @return Bool to indicate if at limit.
  88749. */
  88750. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  88751. if (!this._attachedCamera) {
  88752. return false;
  88753. }
  88754. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  88755. return true;
  88756. }
  88757. return false;
  88758. };
  88759. /**
  88760. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  88761. * @param radiusDelta The delta by which to animate to. Can be negative.
  88762. */
  88763. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  88764. var _this = this;
  88765. if (!this._attachedCamera) {
  88766. return;
  88767. }
  88768. if (!this._radiusBounceTransition) {
  88769. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  88770. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  88771. }
  88772. // Prevent zoom until bounce has completed
  88773. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  88774. this._attachedCamera.wheelPrecision = Infinity;
  88775. this._attachedCamera.inertialRadiusOffset = 0;
  88776. // Animate to the radius limit
  88777. this.stopAllAnimations();
  88778. this._radiusIsAnimating = true;
  88779. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  88780. if (animatable) {
  88781. this._animatables.push(animatable);
  88782. }
  88783. };
  88784. /**
  88785. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  88786. */
  88787. BouncingBehavior.prototype._clearAnimationLocks = function () {
  88788. this._radiusIsAnimating = false;
  88789. if (this._attachedCamera) {
  88790. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  88791. }
  88792. };
  88793. /**
  88794. * Stops and removes all animations that have been applied to the camera
  88795. */
  88796. BouncingBehavior.prototype.stopAllAnimations = function () {
  88797. if (this._attachedCamera) {
  88798. this._attachedCamera.animations = [];
  88799. }
  88800. while (this._animatables.length) {
  88801. this._animatables[0].onAnimationEnd = null;
  88802. this._animatables[0].stop();
  88803. this._animatables.shift();
  88804. }
  88805. };
  88806. /**
  88807. * The easing function used by animations
  88808. */
  88809. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  88810. /**
  88811. * The easing mode used by animations
  88812. */
  88813. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  88814. return BouncingBehavior;
  88815. }());
  88816. BABYLON.BouncingBehavior = BouncingBehavior;
  88817. })(BABYLON || (BABYLON = {}));
  88818. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  88819. "use strict";
  88820. var BABYLON;
  88821. (function (BABYLON) {
  88822. var AutoRotationBehavior = /** @class */ (function () {
  88823. function AutoRotationBehavior() {
  88824. this._zoomStopsAnimation = false;
  88825. this._idleRotationSpeed = 0.05;
  88826. this._idleRotationWaitTime = 2000;
  88827. this._idleRotationSpinupTime = 2000;
  88828. this._isPointerDown = false;
  88829. this._lastFrameTime = null;
  88830. this._lastInteractionTime = -Infinity;
  88831. this._cameraRotationSpeed = 0;
  88832. this._lastFrameRadius = 0;
  88833. }
  88834. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  88835. get: function () {
  88836. return "AutoRotation";
  88837. },
  88838. enumerable: true,
  88839. configurable: true
  88840. });
  88841. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  88842. /**
  88843. * Gets the flag that indicates if user zooming should stop animation.
  88844. */
  88845. get: function () {
  88846. return this._zoomStopsAnimation;
  88847. },
  88848. /**
  88849. * Sets the flag that indicates if user zooming should stop animation.
  88850. */
  88851. set: function (flag) {
  88852. this._zoomStopsAnimation = flag;
  88853. },
  88854. enumerable: true,
  88855. configurable: true
  88856. });
  88857. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  88858. /**
  88859. * Gets the default speed at which the camera rotates around the model.
  88860. */
  88861. get: function () {
  88862. return this._idleRotationSpeed;
  88863. },
  88864. /**
  88865. * Sets the default speed at which the camera rotates around the model.
  88866. */
  88867. set: function (speed) {
  88868. this._idleRotationSpeed = speed;
  88869. },
  88870. enumerable: true,
  88871. configurable: true
  88872. });
  88873. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  88874. /**
  88875. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  88876. */
  88877. get: function () {
  88878. return this._idleRotationWaitTime;
  88879. },
  88880. /**
  88881. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  88882. */
  88883. set: function (time) {
  88884. this._idleRotationWaitTime = time;
  88885. },
  88886. enumerable: true,
  88887. configurable: true
  88888. });
  88889. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  88890. /**
  88891. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  88892. */
  88893. get: function () {
  88894. return this._idleRotationSpinupTime;
  88895. },
  88896. /**
  88897. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  88898. */
  88899. set: function (time) {
  88900. this._idleRotationSpinupTime = time;
  88901. },
  88902. enumerable: true,
  88903. configurable: true
  88904. });
  88905. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  88906. /**
  88907. * Gets a value indicating if the camera is currently rotating because of this behavior
  88908. */
  88909. get: function () {
  88910. return Math.abs(this._cameraRotationSpeed) > 0;
  88911. },
  88912. enumerable: true,
  88913. configurable: true
  88914. });
  88915. AutoRotationBehavior.prototype.init = function () {
  88916. // Do notihng
  88917. };
  88918. AutoRotationBehavior.prototype.attach = function (camera) {
  88919. var _this = this;
  88920. this._attachedCamera = camera;
  88921. var scene = this._attachedCamera.getScene();
  88922. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  88923. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88924. _this._isPointerDown = true;
  88925. return;
  88926. }
  88927. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  88928. _this._isPointerDown = false;
  88929. }
  88930. });
  88931. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  88932. var now = BABYLON.Tools.Now;
  88933. var dt = 0;
  88934. if (_this._lastFrameTime != null) {
  88935. dt = now - _this._lastFrameTime;
  88936. }
  88937. _this._lastFrameTime = now;
  88938. // Stop the animation if there is user interaction and the animation should stop for this interaction
  88939. _this._applyUserInteraction();
  88940. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  88941. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  88942. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  88943. // Step camera rotation by rotation speed
  88944. if (_this._attachedCamera) {
  88945. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  88946. }
  88947. });
  88948. };
  88949. AutoRotationBehavior.prototype.detach = function () {
  88950. if (!this._attachedCamera) {
  88951. return;
  88952. }
  88953. var scene = this._attachedCamera.getScene();
  88954. if (this._onPrePointerObservableObserver) {
  88955. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  88956. }
  88957. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  88958. this._attachedCamera = null;
  88959. };
  88960. /**
  88961. * Returns true if user is scrolling.
  88962. * @return true if user is scrolling.
  88963. */
  88964. AutoRotationBehavior.prototype._userIsZooming = function () {
  88965. if (!this._attachedCamera) {
  88966. return false;
  88967. }
  88968. return this._attachedCamera.inertialRadiusOffset !== 0;
  88969. };
  88970. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  88971. if (!this._attachedCamera) {
  88972. return false;
  88973. }
  88974. var zoomHasHitLimit = false;
  88975. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  88976. zoomHasHitLimit = true;
  88977. }
  88978. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  88979. this._lastFrameRadius = this._attachedCamera.radius;
  88980. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  88981. };
  88982. /**
  88983. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  88984. */
  88985. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  88986. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  88987. this._lastInteractionTime = BABYLON.Tools.Now;
  88988. }
  88989. };
  88990. // Tools
  88991. AutoRotationBehavior.prototype._userIsMoving = function () {
  88992. if (!this._attachedCamera) {
  88993. return false;
  88994. }
  88995. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  88996. this._attachedCamera.inertialBetaOffset !== 0 ||
  88997. this._attachedCamera.inertialRadiusOffset !== 0 ||
  88998. this._attachedCamera.inertialPanningX !== 0 ||
  88999. this._attachedCamera.inertialPanningY !== 0 ||
  89000. this._isPointerDown;
  89001. };
  89002. return AutoRotationBehavior;
  89003. }());
  89004. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  89005. })(BABYLON || (BABYLON = {}));
  89006. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  89007. "use strict";
  89008. var BABYLON;
  89009. (function (BABYLON) {
  89010. /**
  89011. * This class can be used to get instrumentation data from a Babylon engine
  89012. */
  89013. var EngineInstrumentation = /** @class */ (function () {
  89014. function EngineInstrumentation(engine) {
  89015. this.engine = engine;
  89016. this._captureGPUFrameTime = false;
  89017. this._gpuFrameTime = new BABYLON.PerfCounter();
  89018. this._captureShaderCompilationTime = false;
  89019. this._shaderCompilationTime = new BABYLON.PerfCounter();
  89020. // Observers
  89021. this._onBeginFrameObserver = null;
  89022. this._onEndFrameObserver = null;
  89023. this._onBeforeShaderCompilationObserver = null;
  89024. this._onAfterShaderCompilationObserver = null;
  89025. }
  89026. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  89027. // Properties
  89028. /**
  89029. * Gets the perf counter used for GPU frame time
  89030. */
  89031. get: function () {
  89032. return this._gpuFrameTime;
  89033. },
  89034. enumerable: true,
  89035. configurable: true
  89036. });
  89037. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  89038. /**
  89039. * Gets the GPU frame time capture status
  89040. */
  89041. get: function () {
  89042. return this._captureGPUFrameTime;
  89043. },
  89044. /**
  89045. * Enable or disable the GPU frame time capture
  89046. */
  89047. set: function (value) {
  89048. var _this = this;
  89049. if (value === this._captureGPUFrameTime) {
  89050. return;
  89051. }
  89052. this._captureGPUFrameTime = value;
  89053. if (value) {
  89054. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  89055. if (!_this._gpuFrameTimeToken) {
  89056. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  89057. }
  89058. });
  89059. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  89060. if (!_this._gpuFrameTimeToken) {
  89061. return;
  89062. }
  89063. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  89064. if (time > -1) {
  89065. _this._gpuFrameTimeToken = null;
  89066. _this._gpuFrameTime.fetchNewFrame();
  89067. _this._gpuFrameTime.addCount(time, true);
  89068. }
  89069. });
  89070. }
  89071. else {
  89072. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  89073. this._onBeginFrameObserver = null;
  89074. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  89075. this._onEndFrameObserver = null;
  89076. }
  89077. },
  89078. enumerable: true,
  89079. configurable: true
  89080. });
  89081. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  89082. /**
  89083. * Gets the perf counter used for shader compilation time
  89084. */
  89085. get: function () {
  89086. return this._shaderCompilationTime;
  89087. },
  89088. enumerable: true,
  89089. configurable: true
  89090. });
  89091. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  89092. /**
  89093. * Gets the shader compilation time capture status
  89094. */
  89095. get: function () {
  89096. return this._captureShaderCompilationTime;
  89097. },
  89098. /**
  89099. * Enable or disable the shader compilation time capture
  89100. */
  89101. set: function (value) {
  89102. var _this = this;
  89103. if (value === this._captureShaderCompilationTime) {
  89104. return;
  89105. }
  89106. this._captureShaderCompilationTime = value;
  89107. if (value) {
  89108. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  89109. _this._shaderCompilationTime.fetchNewFrame();
  89110. _this._shaderCompilationTime.beginMonitoring();
  89111. });
  89112. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  89113. _this._shaderCompilationTime.endMonitoring();
  89114. });
  89115. }
  89116. else {
  89117. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  89118. this._onBeforeShaderCompilationObserver = null;
  89119. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  89120. this._onAfterShaderCompilationObserver = null;
  89121. }
  89122. },
  89123. enumerable: true,
  89124. configurable: true
  89125. });
  89126. EngineInstrumentation.prototype.dispose = function () {
  89127. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  89128. this._onBeginFrameObserver = null;
  89129. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  89130. this._onEndFrameObserver = null;
  89131. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  89132. this._onBeforeShaderCompilationObserver = null;
  89133. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  89134. this._onAfterShaderCompilationObserver = null;
  89135. this.engine = null;
  89136. };
  89137. return EngineInstrumentation;
  89138. }());
  89139. BABYLON.EngineInstrumentation = EngineInstrumentation;
  89140. })(BABYLON || (BABYLON = {}));
  89141. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  89142. "use strict";
  89143. var BABYLON;
  89144. (function (BABYLON) {
  89145. /**
  89146. * This class can be used to get instrumentation data from a Babylon engine
  89147. */
  89148. var SceneInstrumentation = /** @class */ (function () {
  89149. function SceneInstrumentation(scene) {
  89150. var _this = this;
  89151. this.scene = scene;
  89152. this._captureActiveMeshesEvaluationTime = false;
  89153. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  89154. this._captureRenderTargetsRenderTime = false;
  89155. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  89156. this._captureFrameTime = false;
  89157. this._frameTime = new BABYLON.PerfCounter();
  89158. this._captureRenderTime = false;
  89159. this._renderTime = new BABYLON.PerfCounter();
  89160. this._captureInterFrameTime = false;
  89161. this._interFrameTime = new BABYLON.PerfCounter();
  89162. this._captureParticlesRenderTime = false;
  89163. this._particlesRenderTime = new BABYLON.PerfCounter();
  89164. this._captureSpritesRenderTime = false;
  89165. this._spritesRenderTime = new BABYLON.PerfCounter();
  89166. this._capturePhysicsTime = false;
  89167. this._physicsTime = new BABYLON.PerfCounter();
  89168. this._captureAnimationsTime = false;
  89169. this._animationsTime = new BABYLON.PerfCounter();
  89170. // Observers
  89171. this._onBeforeActiveMeshesEvaluationObserver = null;
  89172. this._onAfterActiveMeshesEvaluationObserver = null;
  89173. this._onBeforeRenderTargetsRenderObserver = null;
  89174. this._onAfterRenderTargetsRenderObserver = null;
  89175. this._onAfterRenderObserver = null;
  89176. this._onBeforeDrawPhaseObserver = null;
  89177. this._onAfterDrawPhaseObserver = null;
  89178. this._onBeforeAnimationsObserver = null;
  89179. this._onBeforeParticlesRenderingObserver = null;
  89180. this._onAfterParticlesRenderingObserver = null;
  89181. this._onBeforeSpritesRenderingObserver = null;
  89182. this._onAfterSpritesRenderingObserver = null;
  89183. this._onBeforePhysicsObserver = null;
  89184. this._onAfterPhysicsObserver = null;
  89185. this._onAfterAnimationsObserver = null;
  89186. // Before render
  89187. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  89188. if (_this._captureActiveMeshesEvaluationTime) {
  89189. _this._activeMeshesEvaluationTime.fetchNewFrame();
  89190. }
  89191. if (_this._captureRenderTargetsRenderTime) {
  89192. _this._renderTargetsRenderTime.fetchNewFrame();
  89193. }
  89194. if (_this._captureFrameTime) {
  89195. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  89196. _this._frameTime.beginMonitoring();
  89197. }
  89198. if (_this._captureInterFrameTime) {
  89199. _this._interFrameTime.endMonitoring();
  89200. }
  89201. if (_this._captureParticlesRenderTime) {
  89202. _this._particlesRenderTime.fetchNewFrame();
  89203. }
  89204. if (_this._captureSpritesRenderTime) {
  89205. _this._spritesRenderTime.fetchNewFrame();
  89206. }
  89207. if (_this._captureAnimationsTime) {
  89208. _this._animationsTime.beginMonitoring();
  89209. }
  89210. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  89211. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  89212. });
  89213. // After render
  89214. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  89215. if (_this._captureFrameTime) {
  89216. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  89217. _this._frameTime.endMonitoring();
  89218. }
  89219. if (_this._captureRenderTime) {
  89220. _this._renderTime.endMonitoring(false);
  89221. }
  89222. if (_this._captureInterFrameTime) {
  89223. _this._interFrameTime.beginMonitoring();
  89224. }
  89225. });
  89226. }
  89227. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  89228. // Properties
  89229. /**
  89230. * Gets the perf counter used for active meshes evaluation time
  89231. */
  89232. get: function () {
  89233. return this._activeMeshesEvaluationTime;
  89234. },
  89235. enumerable: true,
  89236. configurable: true
  89237. });
  89238. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  89239. /**
  89240. * Gets the active meshes evaluation time capture status
  89241. */
  89242. get: function () {
  89243. return this._captureActiveMeshesEvaluationTime;
  89244. },
  89245. /**
  89246. * Enable or disable the active meshes evaluation time capture
  89247. */
  89248. set: function (value) {
  89249. var _this = this;
  89250. if (value === this._captureActiveMeshesEvaluationTime) {
  89251. return;
  89252. }
  89253. this._captureActiveMeshesEvaluationTime = value;
  89254. if (value) {
  89255. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  89256. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  89257. _this._activeMeshesEvaluationTime.beginMonitoring();
  89258. });
  89259. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  89260. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  89261. _this._activeMeshesEvaluationTime.endMonitoring();
  89262. });
  89263. }
  89264. else {
  89265. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  89266. this._onBeforeActiveMeshesEvaluationObserver = null;
  89267. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  89268. this._onAfterActiveMeshesEvaluationObserver = null;
  89269. }
  89270. },
  89271. enumerable: true,
  89272. configurable: true
  89273. });
  89274. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  89275. /**
  89276. * Gets the perf counter used for render targets render time
  89277. */
  89278. get: function () {
  89279. return this._renderTargetsRenderTime;
  89280. },
  89281. enumerable: true,
  89282. configurable: true
  89283. });
  89284. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  89285. /**
  89286. * Gets the render targets render time capture status
  89287. */
  89288. get: function () {
  89289. return this._captureRenderTargetsRenderTime;
  89290. },
  89291. /**
  89292. * Enable or disable the render targets render time capture
  89293. */
  89294. set: function (value) {
  89295. var _this = this;
  89296. if (value === this._captureRenderTargetsRenderTime) {
  89297. return;
  89298. }
  89299. this._captureRenderTargetsRenderTime = value;
  89300. if (value) {
  89301. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  89302. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  89303. _this._renderTargetsRenderTime.beginMonitoring();
  89304. });
  89305. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  89306. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  89307. _this._renderTargetsRenderTime.endMonitoring(false);
  89308. });
  89309. }
  89310. else {
  89311. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  89312. this._onBeforeRenderTargetsRenderObserver = null;
  89313. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  89314. this._onAfterRenderTargetsRenderObserver = null;
  89315. }
  89316. },
  89317. enumerable: true,
  89318. configurable: true
  89319. });
  89320. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  89321. /**
  89322. * Gets the perf counter used for particles render time
  89323. */
  89324. get: function () {
  89325. return this._particlesRenderTime;
  89326. },
  89327. enumerable: true,
  89328. configurable: true
  89329. });
  89330. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  89331. /**
  89332. * Gets the particles render time capture status
  89333. */
  89334. get: function () {
  89335. return this._captureParticlesRenderTime;
  89336. },
  89337. /**
  89338. * Enable or disable the particles render time capture
  89339. */
  89340. set: function (value) {
  89341. var _this = this;
  89342. if (value === this._captureParticlesRenderTime) {
  89343. return;
  89344. }
  89345. this._captureParticlesRenderTime = value;
  89346. if (value) {
  89347. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  89348. BABYLON.Tools.StartPerformanceCounter("Particles");
  89349. _this._particlesRenderTime.beginMonitoring();
  89350. });
  89351. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  89352. BABYLON.Tools.EndPerformanceCounter("Particles");
  89353. _this._particlesRenderTime.endMonitoring(false);
  89354. });
  89355. }
  89356. else {
  89357. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  89358. this._onBeforeParticlesRenderingObserver = null;
  89359. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  89360. this._onAfterParticlesRenderingObserver = null;
  89361. }
  89362. },
  89363. enumerable: true,
  89364. configurable: true
  89365. });
  89366. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  89367. /**
  89368. * Gets the perf counter used for sprites render time
  89369. */
  89370. get: function () {
  89371. return this._spritesRenderTime;
  89372. },
  89373. enumerable: true,
  89374. configurable: true
  89375. });
  89376. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  89377. /**
  89378. * Gets the sprites render time capture status
  89379. */
  89380. get: function () {
  89381. return this._captureSpritesRenderTime;
  89382. },
  89383. /**
  89384. * Enable or disable the sprites render time capture
  89385. */
  89386. set: function (value) {
  89387. var _this = this;
  89388. if (value === this._captureSpritesRenderTime) {
  89389. return;
  89390. }
  89391. this._captureSpritesRenderTime = value;
  89392. if (value) {
  89393. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  89394. BABYLON.Tools.StartPerformanceCounter("Sprites");
  89395. _this._spritesRenderTime.beginMonitoring();
  89396. });
  89397. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  89398. BABYLON.Tools.EndPerformanceCounter("Sprites");
  89399. _this._spritesRenderTime.endMonitoring(false);
  89400. });
  89401. }
  89402. else {
  89403. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  89404. this._onBeforeSpritesRenderingObserver = null;
  89405. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  89406. this._onAfterSpritesRenderingObserver = null;
  89407. }
  89408. },
  89409. enumerable: true,
  89410. configurable: true
  89411. });
  89412. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  89413. /**
  89414. * Gets the perf counter used for physics time
  89415. */
  89416. get: function () {
  89417. return this._physicsTime;
  89418. },
  89419. enumerable: true,
  89420. configurable: true
  89421. });
  89422. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  89423. /**
  89424. * Gets the physics time capture status
  89425. */
  89426. get: function () {
  89427. return this._capturePhysicsTime;
  89428. },
  89429. /**
  89430. * Enable or disable the physics time capture
  89431. */
  89432. set: function (value) {
  89433. var _this = this;
  89434. if (value === this._capturePhysicsTime) {
  89435. return;
  89436. }
  89437. this._capturePhysicsTime = value;
  89438. if (value) {
  89439. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  89440. BABYLON.Tools.StartPerformanceCounter("Physics");
  89441. _this._physicsTime.beginMonitoring();
  89442. });
  89443. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  89444. BABYLON.Tools.EndPerformanceCounter("Physics");
  89445. _this._physicsTime.endMonitoring();
  89446. });
  89447. }
  89448. else {
  89449. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  89450. this._onBeforePhysicsObserver = null;
  89451. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  89452. this._onAfterPhysicsObserver = null;
  89453. }
  89454. },
  89455. enumerable: true,
  89456. configurable: true
  89457. });
  89458. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  89459. /**
  89460. * Gets the perf counter used for animations time
  89461. */
  89462. get: function () {
  89463. return this._animationsTime;
  89464. },
  89465. enumerable: true,
  89466. configurable: true
  89467. });
  89468. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  89469. /**
  89470. * Gets the animations time capture status
  89471. */
  89472. get: function () {
  89473. return this._captureAnimationsTime;
  89474. },
  89475. /**
  89476. * Enable or disable the animations time capture
  89477. */
  89478. set: function (value) {
  89479. var _this = this;
  89480. if (value === this._captureAnimationsTime) {
  89481. return;
  89482. }
  89483. this._captureAnimationsTime = value;
  89484. if (value) {
  89485. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  89486. _this._animationsTime.endMonitoring();
  89487. });
  89488. }
  89489. else {
  89490. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  89491. this._onAfterAnimationsObserver = null;
  89492. }
  89493. },
  89494. enumerable: true,
  89495. configurable: true
  89496. });
  89497. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  89498. /**
  89499. * Gets the perf counter used for frame time capture
  89500. */
  89501. get: function () {
  89502. return this._frameTime;
  89503. },
  89504. enumerable: true,
  89505. configurable: true
  89506. });
  89507. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  89508. /**
  89509. * Gets the frame time capture status
  89510. */
  89511. get: function () {
  89512. return this._captureFrameTime;
  89513. },
  89514. /**
  89515. * Enable or disable the frame time capture
  89516. */
  89517. set: function (value) {
  89518. this._captureFrameTime = value;
  89519. },
  89520. enumerable: true,
  89521. configurable: true
  89522. });
  89523. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  89524. /**
  89525. * Gets the perf counter used for inter-frames time capture
  89526. */
  89527. get: function () {
  89528. return this._interFrameTime;
  89529. },
  89530. enumerable: true,
  89531. configurable: true
  89532. });
  89533. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  89534. /**
  89535. * Gets the inter-frames time capture status
  89536. */
  89537. get: function () {
  89538. return this._captureInterFrameTime;
  89539. },
  89540. /**
  89541. * Enable or disable the inter-frames time capture
  89542. */
  89543. set: function (value) {
  89544. this._captureInterFrameTime = value;
  89545. },
  89546. enumerable: true,
  89547. configurable: true
  89548. });
  89549. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  89550. /**
  89551. * Gets the perf counter used for render time capture
  89552. */
  89553. get: function () {
  89554. return this._renderTime;
  89555. },
  89556. enumerable: true,
  89557. configurable: true
  89558. });
  89559. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  89560. /**
  89561. * Gets the render time capture status
  89562. */
  89563. get: function () {
  89564. return this._captureRenderTime;
  89565. },
  89566. /**
  89567. * Enable or disable the render time capture
  89568. */
  89569. set: function (value) {
  89570. var _this = this;
  89571. if (value === this._captureRenderTime) {
  89572. return;
  89573. }
  89574. this._captureRenderTime = value;
  89575. if (value) {
  89576. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  89577. _this._renderTime.beginMonitoring();
  89578. BABYLON.Tools.StartPerformanceCounter("Main render");
  89579. });
  89580. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  89581. _this._renderTime.endMonitoring(false);
  89582. BABYLON.Tools.EndPerformanceCounter("Main render");
  89583. });
  89584. }
  89585. else {
  89586. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  89587. this._onBeforeDrawPhaseObserver = null;
  89588. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  89589. this._onAfterDrawPhaseObserver = null;
  89590. }
  89591. },
  89592. enumerable: true,
  89593. configurable: true
  89594. });
  89595. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  89596. /**
  89597. * Gets the perf counter used for draw calls
  89598. */
  89599. get: function () {
  89600. return this.scene.getEngine()._drawCalls;
  89601. },
  89602. enumerable: true,
  89603. configurable: true
  89604. });
  89605. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  89606. /**
  89607. * Gets the perf counter used for texture collisions
  89608. */
  89609. get: function () {
  89610. return this.scene.getEngine()._textureCollisions;
  89611. },
  89612. enumerable: true,
  89613. configurable: true
  89614. });
  89615. SceneInstrumentation.prototype.dispose = function () {
  89616. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  89617. this._onAfterRenderObserver = null;
  89618. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  89619. this._onBeforeActiveMeshesEvaluationObserver = null;
  89620. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  89621. this._onAfterActiveMeshesEvaluationObserver = null;
  89622. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  89623. this._onBeforeRenderTargetsRenderObserver = null;
  89624. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  89625. this._onAfterRenderTargetsRenderObserver = null;
  89626. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  89627. this._onBeforeAnimationsObserver = null;
  89628. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  89629. this._onBeforeParticlesRenderingObserver = null;
  89630. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  89631. this._onAfterParticlesRenderingObserver = null;
  89632. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  89633. this._onBeforeSpritesRenderingObserver = null;
  89634. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  89635. this._onAfterSpritesRenderingObserver = null;
  89636. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  89637. this._onBeforeDrawPhaseObserver = null;
  89638. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  89639. this._onAfterDrawPhaseObserver = null;
  89640. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  89641. this._onBeforePhysicsObserver = null;
  89642. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  89643. this._onAfterPhysicsObserver = null;
  89644. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  89645. this._onAfterAnimationsObserver = null;
  89646. this.scene = null;
  89647. };
  89648. return SceneInstrumentation;
  89649. }());
  89650. BABYLON.SceneInstrumentation = SceneInstrumentation;
  89651. })(BABYLON || (BABYLON = {}));
  89652. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  89653. "use strict";
  89654. var BABYLON;
  89655. (function (BABYLON) {
  89656. var _TimeToken = /** @class */ (function () {
  89657. function _TimeToken() {
  89658. this._timeElapsedQueryEnded = false;
  89659. }
  89660. return _TimeToken;
  89661. }());
  89662. BABYLON._TimeToken = _TimeToken;
  89663. })(BABYLON || (BABYLON = {}));
  89664. //# sourceMappingURL=babylon.timeToken.js.map
  89665. "use strict";
  89666. var BABYLON;
  89667. (function (BABYLON) {
  89668. /**
  89669. * Background material defines definition.
  89670. * @ignore Mainly internal Use
  89671. */
  89672. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  89673. __extends(BackgroundMaterialDefines, _super);
  89674. /**
  89675. * Constructor of the defines.
  89676. */
  89677. function BackgroundMaterialDefines() {
  89678. var _this = _super.call(this) || this;
  89679. /**
  89680. * True if the diffuse texture is in use.
  89681. */
  89682. _this.DIFFUSE = false;
  89683. /**
  89684. * The direct UV channel to use.
  89685. */
  89686. _this.DIFFUSEDIRECTUV = 0;
  89687. /**
  89688. * True if the diffuse texture is in gamma space.
  89689. */
  89690. _this.GAMMADIFFUSE = false;
  89691. /**
  89692. * True if the diffuse texture has opacity in the alpha channel.
  89693. */
  89694. _this.DIFFUSEHASALPHA = false;
  89695. /**
  89696. * True if you want the material to fade to transparent at grazing angle.
  89697. */
  89698. _this.OPACITYFRESNEL = false;
  89699. /**
  89700. * True if an extra blur needs to be added in the reflection.
  89701. */
  89702. _this.REFLECTIONBLUR = false;
  89703. /**
  89704. * True if you want the material to fade to reflection at grazing angle.
  89705. */
  89706. _this.REFLECTIONFRESNEL = false;
  89707. /**
  89708. * True if you want the material to falloff as far as you move away from the scene center.
  89709. */
  89710. _this.REFLECTIONFALLOFF = false;
  89711. /**
  89712. * False if the current Webgl implementation does not support the texture lod extension.
  89713. */
  89714. _this.TEXTURELODSUPPORT = false;
  89715. /**
  89716. * True to ensure the data are premultiplied.
  89717. */
  89718. _this.PREMULTIPLYALPHA = false;
  89719. /**
  89720. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  89721. */
  89722. _this.USERGBCOLOR = false;
  89723. /**
  89724. * True to add noise in order to reduce the banding effect.
  89725. */
  89726. _this.NOISE = false;
  89727. /**
  89728. * is the reflection texture in BGR color scheme?
  89729. * Mainly used to solve a bug in ios10 video tag
  89730. */
  89731. _this.REFLECTIONBGR = false;
  89732. _this.IMAGEPROCESSING = false;
  89733. _this.VIGNETTE = false;
  89734. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  89735. _this.VIGNETTEBLENDMODEOPAQUE = false;
  89736. _this.TONEMAPPING = false;
  89737. _this.CONTRAST = false;
  89738. _this.COLORCURVES = false;
  89739. _this.COLORGRADING = false;
  89740. _this.COLORGRADING3D = false;
  89741. _this.SAMPLER3DGREENDEPTH = false;
  89742. _this.SAMPLER3DBGRMAP = false;
  89743. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  89744. _this.EXPOSURE = false;
  89745. _this.GRAIN = false;
  89746. // Reflection.
  89747. _this.REFLECTION = false;
  89748. _this.REFLECTIONMAP_3D = false;
  89749. _this.REFLECTIONMAP_SPHERICAL = false;
  89750. _this.REFLECTIONMAP_PLANAR = false;
  89751. _this.REFLECTIONMAP_CUBIC = false;
  89752. _this.REFLECTIONMAP_PROJECTION = false;
  89753. _this.REFLECTIONMAP_SKYBOX = false;
  89754. _this.REFLECTIONMAP_EXPLICIT = false;
  89755. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  89756. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  89757. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  89758. _this.INVERTCUBICMAP = false;
  89759. _this.REFLECTIONMAP_OPPOSITEZ = false;
  89760. _this.LODINREFLECTIONALPHA = false;
  89761. _this.GAMMAREFLECTION = false;
  89762. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  89763. // Default BJS.
  89764. _this.MAINUV1 = false;
  89765. _this.MAINUV2 = false;
  89766. _this.UV1 = false;
  89767. _this.UV2 = false;
  89768. _this.CLIPPLANE = false;
  89769. _this.POINTSIZE = false;
  89770. _this.FOG = false;
  89771. _this.NORMAL = false;
  89772. _this.NUM_BONE_INFLUENCERS = 0;
  89773. _this.BonesPerMesh = 0;
  89774. _this.INSTANCES = false;
  89775. _this.SHADOWFLOAT = false;
  89776. _this.rebuild();
  89777. return _this;
  89778. }
  89779. return BackgroundMaterialDefines;
  89780. }(BABYLON.MaterialDefines));
  89781. /**
  89782. * Background material used to create an efficient environement around your scene.
  89783. */
  89784. var BackgroundMaterial = /** @class */ (function (_super) {
  89785. __extends(BackgroundMaterial, _super);
  89786. /**
  89787. * Instantiates a Background Material in the given scene
  89788. * @param name The friendly name of the material
  89789. * @param scene The scene to add the material to
  89790. */
  89791. function BackgroundMaterial(name, scene) {
  89792. var _this = _super.call(this, name, scene) || this;
  89793. /**
  89794. * Key light Color (multiply against the R channel of the environement texture)
  89795. */
  89796. _this.primaryColor = BABYLON.Color3.White();
  89797. /**
  89798. * Key light Level (allowing HDR output of the background)
  89799. */
  89800. _this.primaryLevel = 1;
  89801. /**
  89802. * Secondary light Color (multiply against the G channel of the environement texture)
  89803. */
  89804. _this.secondaryColor = BABYLON.Color3.Gray();
  89805. /**
  89806. * Secondary light Level (allowing HDR output of the background)
  89807. */
  89808. _this.secondaryLevel = 1;
  89809. /**
  89810. * Tertiary light Color (multiply against the B channel of the environement texture)
  89811. */
  89812. _this.tertiaryColor = BABYLON.Color3.Black();
  89813. /**
  89814. * Tertiary light Level (allowing HDR output of the background)
  89815. */
  89816. _this.tertiaryLevel = 1;
  89817. /**
  89818. * Reflection Texture used in the material.
  89819. * Should be author in a specific way for the best result (refer to the documentation).
  89820. */
  89821. _this.reflectionTexture = null;
  89822. /**
  89823. * Reflection Texture level of blur.
  89824. *
  89825. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  89826. * texture twice.
  89827. */
  89828. _this.reflectionBlur = 0;
  89829. /**
  89830. * Diffuse Texture used in the material.
  89831. * Should be author in a specific way for the best result (refer to the documentation).
  89832. */
  89833. _this.diffuseTexture = null;
  89834. _this._shadowLights = null;
  89835. /**
  89836. * Specify the list of lights casting shadow on the material.
  89837. * All scene shadow lights will be included if null.
  89838. */
  89839. _this.shadowLights = null;
  89840. /**
  89841. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  89842. * soft lighting on the background.
  89843. */
  89844. _this.shadowBlurScale = 1;
  89845. /**
  89846. * Helps adjusting the shadow to a softer level if required.
  89847. * 0 means black shadows and 1 means no shadows.
  89848. */
  89849. _this.shadowLevel = 0;
  89850. /**
  89851. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  89852. * It is usually zero but might be interesting to modify according to your setup.
  89853. */
  89854. _this.sceneCenter = BABYLON.Vector3.Zero();
  89855. /**
  89856. * This helps specifying that the material is falling off to the sky box at grazing angle.
  89857. * This helps ensuring a nice transition when the camera goes under the ground.
  89858. */
  89859. _this.opacityFresnel = true;
  89860. /**
  89861. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  89862. * This helps adding a mirror texture on the ground.
  89863. */
  89864. _this.reflectionFresnel = false;
  89865. /**
  89866. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  89867. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  89868. */
  89869. _this.reflectionFalloffDistance = 0.0;
  89870. /**
  89871. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  89872. */
  89873. _this.reflectionAmount = 1.0;
  89874. /**
  89875. * This specifies the weight of the reflection at grazing angle.
  89876. */
  89877. _this.reflectionReflectance0 = 0.05;
  89878. /**
  89879. * This specifies the weight of the reflection at a perpendicular point of view.
  89880. */
  89881. _this.reflectionReflectance90 = 0.5;
  89882. /**
  89883. * Helps to directly use the maps channels instead of their level.
  89884. */
  89885. _this.useRGBColor = true;
  89886. /**
  89887. * This helps reducing the banding effect that could occur on the background.
  89888. */
  89889. _this.enableNoise = false;
  89890. _this._fovMultiplier = 1.0;
  89891. /**
  89892. * Enable the FOV adjustment feature controlled by fovMultiplier.
  89893. * @type {boolean}
  89894. */
  89895. _this.useEquirectangularFOV = false;
  89896. _this._maxSimultaneousLights = 4;
  89897. /**
  89898. * Number of Simultaneous lights allowed on the material.
  89899. */
  89900. _this.maxSimultaneousLights = 4;
  89901. /**
  89902. * Keep track of the image processing observer to allow dispose and replace.
  89903. */
  89904. _this._imageProcessingObserver = null;
  89905. /**
  89906. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  89907. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  89908. */
  89909. _this.switchToBGR = false;
  89910. // Temp values kept as cache in the material.
  89911. _this._renderTargets = new BABYLON.SmartArray(16);
  89912. _this._reflectionControls = BABYLON.Vector4.Zero();
  89913. // Setup the default processing configuration to the scene.
  89914. _this._attachImageProcessingConfiguration(null);
  89915. _this.getRenderTargetTextures = function () {
  89916. _this._renderTargets.reset();
  89917. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  89918. _this._renderTargets.push(_this._diffuseTexture);
  89919. }
  89920. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  89921. _this._renderTargets.push(_this._reflectionTexture);
  89922. }
  89923. return _this._renderTargets;
  89924. };
  89925. return _this;
  89926. }
  89927. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  89928. /**
  89929. * Sets the reflection reflectance fresnel values according to the default standard
  89930. * empirically know to work well :-)
  89931. */
  89932. set: function (value) {
  89933. var reflectionWeight = value;
  89934. if (reflectionWeight < 0.5) {
  89935. reflectionWeight = reflectionWeight * 2.0;
  89936. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  89937. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  89938. }
  89939. else {
  89940. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  89941. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  89942. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  89943. }
  89944. },
  89945. enumerable: true,
  89946. configurable: true
  89947. });
  89948. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  89949. /**
  89950. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  89951. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  89952. * Recommended to be keep at 1.0 except for special cases.
  89953. */
  89954. get: function () {
  89955. return this._fovMultiplier;
  89956. },
  89957. set: function (value) {
  89958. if (isNaN(value)) {
  89959. value = 1.0;
  89960. }
  89961. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  89962. },
  89963. enumerable: true,
  89964. configurable: true
  89965. });
  89966. /**
  89967. * Attaches a new image processing configuration to the PBR Material.
  89968. * @param configuration (if null the scene configuration will be use)
  89969. */
  89970. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  89971. var _this = this;
  89972. if (configuration === this._imageProcessingConfiguration) {
  89973. return;
  89974. }
  89975. // Detaches observer.
  89976. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  89977. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  89978. }
  89979. // Pick the scene configuration if needed.
  89980. if (!configuration) {
  89981. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  89982. }
  89983. else {
  89984. this._imageProcessingConfiguration = configuration;
  89985. }
  89986. // Attaches observer.
  89987. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  89988. _this._markAllSubMeshesAsImageProcessingDirty();
  89989. });
  89990. };
  89991. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  89992. /**
  89993. * Gets the image processing configuration used either in this material.
  89994. */
  89995. get: function () {
  89996. return this._imageProcessingConfiguration;
  89997. },
  89998. /**
  89999. * Sets the Default image processing configuration used either in the this material.
  90000. *
  90001. * If sets to null, the scene one is in use.
  90002. */
  90003. set: function (value) {
  90004. this._attachImageProcessingConfiguration(value);
  90005. // Ensure the effect will be rebuilt.
  90006. this._markAllSubMeshesAsTexturesDirty();
  90007. },
  90008. enumerable: true,
  90009. configurable: true
  90010. });
  90011. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  90012. /**
  90013. * Gets wether the color curves effect is enabled.
  90014. */
  90015. get: function () {
  90016. return this.imageProcessingConfiguration.colorCurvesEnabled;
  90017. },
  90018. /**
  90019. * Sets wether the color curves effect is enabled.
  90020. */
  90021. set: function (value) {
  90022. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  90023. },
  90024. enumerable: true,
  90025. configurable: true
  90026. });
  90027. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  90028. /**
  90029. * Gets wether the color grading effect is enabled.
  90030. */
  90031. get: function () {
  90032. return this.imageProcessingConfiguration.colorGradingEnabled;
  90033. },
  90034. /**
  90035. * Gets wether the color grading effect is enabled.
  90036. */
  90037. set: function (value) {
  90038. this.imageProcessingConfiguration.colorGradingEnabled = value;
  90039. },
  90040. enumerable: true,
  90041. configurable: true
  90042. });
  90043. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  90044. /**
  90045. * Gets wether tonemapping is enabled or not.
  90046. */
  90047. get: function () {
  90048. return this._imageProcessingConfiguration.toneMappingEnabled;
  90049. },
  90050. /**
  90051. * Sets wether tonemapping is enabled or not
  90052. */
  90053. set: function (value) {
  90054. this._imageProcessingConfiguration.toneMappingEnabled = value;
  90055. },
  90056. enumerable: true,
  90057. configurable: true
  90058. });
  90059. ;
  90060. ;
  90061. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  90062. /**
  90063. * The camera exposure used on this material.
  90064. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  90065. * This corresponds to a photographic exposure.
  90066. */
  90067. get: function () {
  90068. return this._imageProcessingConfiguration.exposure;
  90069. },
  90070. /**
  90071. * The camera exposure used on this material.
  90072. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  90073. * This corresponds to a photographic exposure.
  90074. */
  90075. set: function (value) {
  90076. this._imageProcessingConfiguration.exposure = value;
  90077. },
  90078. enumerable: true,
  90079. configurable: true
  90080. });
  90081. ;
  90082. ;
  90083. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  90084. /**
  90085. * Gets The camera contrast used on this material.
  90086. */
  90087. get: function () {
  90088. return this._imageProcessingConfiguration.contrast;
  90089. },
  90090. /**
  90091. * Sets The camera contrast used on this material.
  90092. */
  90093. set: function (value) {
  90094. this._imageProcessingConfiguration.contrast = value;
  90095. },
  90096. enumerable: true,
  90097. configurable: true
  90098. });
  90099. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  90100. /**
  90101. * Gets the Color Grading 2D Lookup Texture.
  90102. */
  90103. get: function () {
  90104. return this._imageProcessingConfiguration.colorGradingTexture;
  90105. },
  90106. /**
  90107. * Sets the Color Grading 2D Lookup Texture.
  90108. */
  90109. set: function (value) {
  90110. this.imageProcessingConfiguration.colorGradingTexture = value;
  90111. },
  90112. enumerable: true,
  90113. configurable: true
  90114. });
  90115. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  90116. /**
  90117. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  90118. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  90119. * 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;
  90120. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  90121. */
  90122. get: function () {
  90123. return this.imageProcessingConfiguration.colorCurves;
  90124. },
  90125. /**
  90126. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  90127. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  90128. * 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;
  90129. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  90130. */
  90131. set: function (value) {
  90132. this.imageProcessingConfiguration.colorCurves = value;
  90133. },
  90134. enumerable: true,
  90135. configurable: true
  90136. });
  90137. /**
  90138. * The entire material has been created in order to prevent overdraw.
  90139. * @returns false
  90140. */
  90141. BackgroundMaterial.prototype.needAlphaTesting = function () {
  90142. return true;
  90143. };
  90144. /**
  90145. * The entire material has been created in order to prevent overdraw.
  90146. * @returns true if blending is enable
  90147. */
  90148. BackgroundMaterial.prototype.needAlphaBlending = function () {
  90149. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  90150. };
  90151. /**
  90152. * Checks wether the material is ready to be rendered for a given mesh.
  90153. * @param mesh The mesh to render
  90154. * @param subMesh The submesh to check against
  90155. * @param useInstances Specify wether or not the material is used with instances
  90156. * @returns true if all the dependencies are ready (Textures, Effects...)
  90157. */
  90158. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  90159. var _this = this;
  90160. if (useInstances === void 0) { useInstances = false; }
  90161. if (subMesh.effect && this.isFrozen) {
  90162. if (this._wasPreviouslyReady) {
  90163. return true;
  90164. }
  90165. }
  90166. if (!subMesh._materialDefines) {
  90167. subMesh._materialDefines = new BackgroundMaterialDefines();
  90168. }
  90169. var scene = this.getScene();
  90170. var defines = subMesh._materialDefines;
  90171. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  90172. if (defines._renderId === scene.getRenderId()) {
  90173. return true;
  90174. }
  90175. }
  90176. var engine = scene.getEngine();
  90177. // Lights
  90178. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  90179. defines._needNormals = true;
  90180. // Textures
  90181. if (defines._areTexturesDirty) {
  90182. defines._needUVs = false;
  90183. if (scene.texturesEnabled) {
  90184. if (scene.getEngine().getCaps().textureLOD) {
  90185. defines.TEXTURELODSUPPORT = true;
  90186. }
  90187. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  90188. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  90189. return false;
  90190. }
  90191. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  90192. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  90193. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  90194. defines.OPACITYFRESNEL = this._opacityFresnel;
  90195. }
  90196. else {
  90197. defines.DIFFUSE = false;
  90198. defines.DIFFUSEHASALPHA = false;
  90199. defines.GAMMADIFFUSE = false;
  90200. defines.OPACITYFRESNEL = false;
  90201. }
  90202. var reflectionTexture = this._reflectionTexture;
  90203. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  90204. if (!reflectionTexture.isReadyOrNotBlocking()) {
  90205. return false;
  90206. }
  90207. defines.REFLECTION = true;
  90208. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  90209. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  90210. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  90211. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  90212. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  90213. defines.REFLECTIONBGR = this.switchToBGR;
  90214. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  90215. defines.INVERTCUBICMAP = true;
  90216. }
  90217. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  90218. switch (reflectionTexture.coordinatesMode) {
  90219. case BABYLON.Texture.CUBIC_MODE:
  90220. case BABYLON.Texture.INVCUBIC_MODE:
  90221. defines.REFLECTIONMAP_CUBIC = true;
  90222. break;
  90223. case BABYLON.Texture.EXPLICIT_MODE:
  90224. defines.REFLECTIONMAP_EXPLICIT = true;
  90225. break;
  90226. case BABYLON.Texture.PLANAR_MODE:
  90227. defines.REFLECTIONMAP_PLANAR = true;
  90228. break;
  90229. case BABYLON.Texture.PROJECTION_MODE:
  90230. defines.REFLECTIONMAP_PROJECTION = true;
  90231. break;
  90232. case BABYLON.Texture.SKYBOX_MODE:
  90233. defines.REFLECTIONMAP_SKYBOX = true;
  90234. break;
  90235. case BABYLON.Texture.SPHERICAL_MODE:
  90236. defines.REFLECTIONMAP_SPHERICAL = true;
  90237. break;
  90238. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  90239. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  90240. break;
  90241. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  90242. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  90243. break;
  90244. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  90245. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  90246. break;
  90247. }
  90248. if (this.reflectionFresnel) {
  90249. defines.REFLECTIONFRESNEL = true;
  90250. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  90251. this._reflectionControls.x = this.reflectionAmount;
  90252. this._reflectionControls.y = this.reflectionReflectance0;
  90253. this._reflectionControls.z = this.reflectionReflectance90;
  90254. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  90255. }
  90256. else {
  90257. defines.REFLECTIONFRESNEL = false;
  90258. defines.REFLECTIONFALLOFF = false;
  90259. }
  90260. }
  90261. else {
  90262. defines.REFLECTION = false;
  90263. defines.REFLECTIONFALLOFF = false;
  90264. defines.REFLECTIONBLUR = false;
  90265. defines.REFLECTIONMAP_3D = false;
  90266. defines.REFLECTIONMAP_SPHERICAL = false;
  90267. defines.REFLECTIONMAP_PLANAR = false;
  90268. defines.REFLECTIONMAP_CUBIC = false;
  90269. defines.REFLECTIONMAP_PROJECTION = false;
  90270. defines.REFLECTIONMAP_SKYBOX = false;
  90271. defines.REFLECTIONMAP_EXPLICIT = false;
  90272. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  90273. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  90274. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  90275. defines.INVERTCUBICMAP = false;
  90276. defines.REFLECTIONMAP_OPPOSITEZ = false;
  90277. defines.LODINREFLECTIONALPHA = false;
  90278. defines.GAMMAREFLECTION = false;
  90279. }
  90280. }
  90281. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  90282. defines.USERGBCOLOR = this._useRGBColor;
  90283. defines.NOISE = this._enableNoise;
  90284. }
  90285. if (defines._areImageProcessingDirty) {
  90286. if (!this._imageProcessingConfiguration.isReady()) {
  90287. return false;
  90288. }
  90289. this._imageProcessingConfiguration.prepareDefines(defines);
  90290. }
  90291. // Misc.
  90292. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  90293. // Values that need to be evaluated on every frame
  90294. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  90295. // Attribs
  90296. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  90297. if (mesh) {
  90298. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  90299. mesh.createNormals(true);
  90300. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  90301. }
  90302. }
  90303. }
  90304. // Get correct effect
  90305. if (defines.isDirty) {
  90306. defines.markAsProcessed();
  90307. scene.resetCachedMaterial();
  90308. // Fallbacks
  90309. var fallbacks = new BABYLON.EffectFallbacks();
  90310. if (defines.FOG) {
  90311. fallbacks.addFallback(0, "FOG");
  90312. }
  90313. if (defines.POINTSIZE) {
  90314. fallbacks.addFallback(1, "POINTSIZE");
  90315. }
  90316. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  90317. if (defines.NUM_BONE_INFLUENCERS > 0) {
  90318. fallbacks.addCPUSkinningFallback(0, mesh);
  90319. }
  90320. //Attributes
  90321. var attribs = [BABYLON.VertexBuffer.PositionKind];
  90322. if (defines.NORMAL) {
  90323. attribs.push(BABYLON.VertexBuffer.NormalKind);
  90324. }
  90325. if (defines.UV1) {
  90326. attribs.push(BABYLON.VertexBuffer.UVKind);
  90327. }
  90328. if (defines.UV2) {
  90329. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90330. }
  90331. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  90332. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  90333. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  90334. "vFogInfos", "vFogColor", "pointSize",
  90335. "vClipPlane", "mBones",
  90336. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  90337. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  90338. "shadowLevel", "alpha",
  90339. "vBackgroundCenter", "vReflectionControl",
  90340. "vDiffuseInfos", "diffuseMatrix",
  90341. ];
  90342. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  90343. var uniformBuffers = ["Material", "Scene"];
  90344. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  90345. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  90346. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  90347. uniformsNames: uniforms,
  90348. uniformBuffersNames: uniformBuffers,
  90349. samplers: samplers,
  90350. defines: defines,
  90351. maxSimultaneousLights: this._maxSimultaneousLights
  90352. });
  90353. var onCompiled = function (effect) {
  90354. if (_this.onCompiled) {
  90355. _this.onCompiled(effect);
  90356. }
  90357. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  90358. };
  90359. var join = defines.toString();
  90360. subMesh.setEffect(scene.getEngine().createEffect("background", {
  90361. attributes: attribs,
  90362. uniformsNames: uniforms,
  90363. uniformBuffersNames: uniformBuffers,
  90364. samplers: samplers,
  90365. defines: join,
  90366. fallbacks: fallbacks,
  90367. onCompiled: onCompiled,
  90368. onError: this.onError,
  90369. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  90370. }, engine), defines);
  90371. this.buildUniformLayout();
  90372. }
  90373. if (!subMesh.effect || !subMesh.effect.isReady()) {
  90374. return false;
  90375. }
  90376. defines._renderId = scene.getRenderId();
  90377. this._wasPreviouslyReady = true;
  90378. return true;
  90379. };
  90380. /**
  90381. * Build the uniform buffer used in the material.
  90382. */
  90383. BackgroundMaterial.prototype.buildUniformLayout = function () {
  90384. // Order is important !
  90385. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  90386. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  90387. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  90388. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  90389. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  90390. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  90391. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  90392. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  90393. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  90394. this._uniformBuffer.addUniform("pointSize", 1);
  90395. this._uniformBuffer.addUniform("shadowLevel", 1);
  90396. this._uniformBuffer.addUniform("alpha", 1);
  90397. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  90398. this._uniformBuffer.addUniform("vReflectionControl", 4);
  90399. this._uniformBuffer.create();
  90400. };
  90401. /**
  90402. * Unbind the material.
  90403. */
  90404. BackgroundMaterial.prototype.unbind = function () {
  90405. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  90406. this._uniformBuffer.setTexture("diffuseSampler", null);
  90407. }
  90408. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  90409. this._uniformBuffer.setTexture("reflectionSampler", null);
  90410. }
  90411. _super.prototype.unbind.call(this);
  90412. };
  90413. /**
  90414. * Bind only the world matrix to the material.
  90415. * @param world The world matrix to bind.
  90416. */
  90417. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  90418. this._activeEffect.setMatrix("world", world);
  90419. };
  90420. /**
  90421. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  90422. * @param world The world matrix to bind.
  90423. * @param subMesh The submesh to bind for.
  90424. */
  90425. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  90426. var scene = this.getScene();
  90427. var defines = subMesh._materialDefines;
  90428. if (!defines) {
  90429. return;
  90430. }
  90431. var effect = subMesh.effect;
  90432. if (!effect) {
  90433. return;
  90434. }
  90435. this._activeEffect = effect;
  90436. // Matrices
  90437. this.bindOnlyWorldMatrix(world);
  90438. // Bones
  90439. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  90440. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  90441. if (mustRebind) {
  90442. this._uniformBuffer.bindToEffect(effect, "Material");
  90443. this.bindViewProjection(effect);
  90444. var reflectionTexture = this._reflectionTexture;
  90445. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  90446. // Texture uniforms
  90447. if (scene.texturesEnabled) {
  90448. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  90449. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  90450. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  90451. }
  90452. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  90453. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  90454. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  90455. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  90456. }
  90457. }
  90458. if (this.shadowLevel > 0) {
  90459. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  90460. }
  90461. this._uniformBuffer.updateFloat("alpha", this.alpha);
  90462. // Point size
  90463. if (this.pointsCloud) {
  90464. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  90465. }
  90466. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  90467. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  90468. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  90469. }
  90470. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  90471. // Textures
  90472. if (scene.texturesEnabled) {
  90473. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  90474. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  90475. }
  90476. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  90477. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  90478. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  90479. }
  90480. else if (!defines.REFLECTIONBLUR) {
  90481. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  90482. }
  90483. else {
  90484. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  90485. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  90486. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  90487. }
  90488. if (defines.REFLECTIONFRESNEL) {
  90489. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  90490. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  90491. }
  90492. }
  90493. }
  90494. // Clip plane
  90495. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  90496. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  90497. }
  90498. if (mustRebind || !this.isFrozen) {
  90499. if (scene.lightsEnabled) {
  90500. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  90501. }
  90502. // View
  90503. this.bindView(effect);
  90504. // Fog
  90505. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  90506. // image processing
  90507. this._imageProcessingConfiguration.bind(this._activeEffect);
  90508. }
  90509. this._uniformBuffer.update();
  90510. this._afterBind(mesh);
  90511. };
  90512. /**
  90513. * Dispose the material.
  90514. * @param forceDisposeEffect Force disposal of the associated effect.
  90515. * @param forceDisposeTextures Force disposal of the associated textures.
  90516. */
  90517. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  90518. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  90519. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  90520. if (forceDisposeTextures) {
  90521. if (this.diffuseTexture) {
  90522. this.diffuseTexture.dispose();
  90523. }
  90524. if (this.reflectionTexture) {
  90525. this.reflectionTexture.dispose();
  90526. }
  90527. }
  90528. this._renderTargets.dispose();
  90529. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  90530. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  90531. }
  90532. _super.prototype.dispose.call(this, forceDisposeEffect);
  90533. };
  90534. /**
  90535. * Clones the material.
  90536. * @param name The cloned name.
  90537. * @returns The cloned material.
  90538. */
  90539. BackgroundMaterial.prototype.clone = function (name) {
  90540. var _this = this;
  90541. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  90542. };
  90543. /**
  90544. * Serializes the current material to its JSON representation.
  90545. * @returns The JSON representation.
  90546. */
  90547. BackgroundMaterial.prototype.serialize = function () {
  90548. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  90549. serializationObject.customType = "BABYLON.BackgroundMaterial";
  90550. return serializationObject;
  90551. };
  90552. /**
  90553. * Gets the class name of the material
  90554. * @returns "BackgroundMaterial"
  90555. */
  90556. BackgroundMaterial.prototype.getClassName = function () {
  90557. return "BackgroundMaterial";
  90558. };
  90559. /**
  90560. * Parse a JSON input to create back a background material.
  90561. * @param source The JSON data to parse
  90562. * @param scene The scene to create the parsed material in
  90563. * @param rootUrl The root url of the assets the material depends upon
  90564. * @returns the instantiated BackgroundMaterial.
  90565. */
  90566. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  90567. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  90568. };
  90569. /**
  90570. * Standard reflectance value at parallel view angle.
  90571. */
  90572. BackgroundMaterial.StandardReflectance0 = 0.05;
  90573. /**
  90574. * Standard reflectance value at grazing angle.
  90575. */
  90576. BackgroundMaterial.StandardReflectance90 = 0.5;
  90577. __decorate([
  90578. BABYLON.serializeAsColor3()
  90579. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  90580. __decorate([
  90581. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90582. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  90583. __decorate([
  90584. BABYLON.serialize()
  90585. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  90586. __decorate([
  90587. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90588. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  90589. __decorate([
  90590. BABYLON.serializeAsColor3()
  90591. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  90592. __decorate([
  90593. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90594. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  90595. __decorate([
  90596. BABYLON.serialize()
  90597. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  90598. __decorate([
  90599. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90600. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  90601. __decorate([
  90602. BABYLON.serializeAsColor3()
  90603. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  90604. __decorate([
  90605. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90606. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  90607. __decorate([
  90608. BABYLON.serialize()
  90609. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  90610. __decorate([
  90611. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90612. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  90613. __decorate([
  90614. BABYLON.serializeAsTexture()
  90615. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  90616. __decorate([
  90617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90618. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  90619. __decorate([
  90620. BABYLON.serialize()
  90621. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  90622. __decorate([
  90623. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90624. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  90625. __decorate([
  90626. BABYLON.serializeAsTexture()
  90627. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  90628. __decorate([
  90629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90630. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  90631. __decorate([
  90632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90633. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  90634. __decorate([
  90635. BABYLON.serialize()
  90636. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  90637. __decorate([
  90638. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90639. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  90640. __decorate([
  90641. BABYLON.serialize()
  90642. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  90643. __decorate([
  90644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90645. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  90646. __decorate([
  90647. BABYLON.serializeAsVector3()
  90648. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  90649. __decorate([
  90650. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90651. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  90652. __decorate([
  90653. BABYLON.serialize()
  90654. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  90655. __decorate([
  90656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90657. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  90658. __decorate([
  90659. BABYLON.serialize()
  90660. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  90661. __decorate([
  90662. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90663. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  90664. __decorate([
  90665. BABYLON.serialize()
  90666. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  90667. __decorate([
  90668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90669. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  90670. __decorate([
  90671. BABYLON.serialize()
  90672. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  90673. __decorate([
  90674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90675. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  90676. __decorate([
  90677. BABYLON.serialize()
  90678. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  90679. __decorate([
  90680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90681. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  90682. __decorate([
  90683. BABYLON.serialize()
  90684. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  90685. __decorate([
  90686. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90687. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  90688. __decorate([
  90689. BABYLON.serialize()
  90690. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  90691. __decorate([
  90692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90693. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  90694. __decorate([
  90695. BABYLON.serialize()
  90696. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  90697. __decorate([
  90698. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90699. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  90700. __decorate([
  90701. BABYLON.serialize()
  90702. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  90703. __decorate([
  90704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90705. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  90706. __decorate([
  90707. BABYLON.serializeAsImageProcessingConfiguration()
  90708. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  90709. return BackgroundMaterial;
  90710. }(BABYLON.PushMaterial));
  90711. BABYLON.BackgroundMaterial = BackgroundMaterial;
  90712. })(BABYLON || (BABYLON = {}));
  90713. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  90714. "use strict";
  90715. var __assign = (this && this.__assign) || Object.assign || function(t) {
  90716. for (var s, i = 1, n = arguments.length; i < n; i++) {
  90717. s = arguments[i];
  90718. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  90719. t[p] = s[p];
  90720. }
  90721. return t;
  90722. };
  90723. var BABYLON;
  90724. (function (BABYLON) {
  90725. /**
  90726. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  90727. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  90728. * It also helps with the default setup of your imageProcessing configuration.
  90729. */
  90730. var EnvironmentHelper = /** @class */ (function () {
  90731. /**
  90732. * constructor
  90733. * @param options
  90734. * @param scene The scene to add the material to
  90735. */
  90736. function EnvironmentHelper(options, scene) {
  90737. var _this = this;
  90738. this._errorHandler = function (message, exception) {
  90739. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  90740. };
  90741. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  90742. this._scene = scene;
  90743. this.onErrorObservable = new BABYLON.Observable();
  90744. this._setupBackground();
  90745. this._setupImageProcessing();
  90746. }
  90747. /**
  90748. * Creates the default options for the helper.
  90749. */
  90750. EnvironmentHelper._getDefaultOptions = function () {
  90751. return {
  90752. createGround: true,
  90753. groundSize: 15,
  90754. groundTexture: this._groundTextureCDNUrl,
  90755. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  90756. groundOpacity: 0.9,
  90757. enableGroundShadow: true,
  90758. groundShadowLevel: 0.5,
  90759. enableGroundMirror: false,
  90760. groundMirrorSizeRatio: 0.3,
  90761. groundMirrorBlurKernel: 64,
  90762. groundMirrorAmount: 1,
  90763. groundMirrorFresnelWeight: 1,
  90764. groundMirrorFallOffDistance: 0,
  90765. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  90766. groundYBias: 0.00001,
  90767. createSkybox: true,
  90768. skyboxSize: 20,
  90769. skyboxTexture: this._skyboxTextureCDNUrl,
  90770. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  90771. backgroundYRotation: 0,
  90772. sizeAuto: true,
  90773. rootPosition: BABYLON.Vector3.Zero(),
  90774. setupImageProcessing: true,
  90775. environmentTexture: this._environmentTextureCDNUrl,
  90776. cameraExposure: 0.8,
  90777. cameraContrast: 1.2,
  90778. toneMappingEnabled: true,
  90779. };
  90780. };
  90781. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  90782. /**
  90783. * Gets the root mesh created by the helper.
  90784. */
  90785. get: function () {
  90786. return this._rootMesh;
  90787. },
  90788. enumerable: true,
  90789. configurable: true
  90790. });
  90791. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  90792. /**
  90793. * Gets the skybox created by the helper.
  90794. */
  90795. get: function () {
  90796. return this._skybox;
  90797. },
  90798. enumerable: true,
  90799. configurable: true
  90800. });
  90801. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  90802. /**
  90803. * Gets the skybox texture created by the helper.
  90804. */
  90805. get: function () {
  90806. return this._skyboxTexture;
  90807. },
  90808. enumerable: true,
  90809. configurable: true
  90810. });
  90811. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  90812. /**
  90813. * Gets the skybox material created by the helper.
  90814. */
  90815. get: function () {
  90816. return this._skyboxMaterial;
  90817. },
  90818. enumerable: true,
  90819. configurable: true
  90820. });
  90821. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  90822. /**
  90823. * Gets the ground mesh created by the helper.
  90824. */
  90825. get: function () {
  90826. return this._ground;
  90827. },
  90828. enumerable: true,
  90829. configurable: true
  90830. });
  90831. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  90832. /**
  90833. * Gets the ground texture created by the helper.
  90834. */
  90835. get: function () {
  90836. return this._groundTexture;
  90837. },
  90838. enumerable: true,
  90839. configurable: true
  90840. });
  90841. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  90842. /**
  90843. * Gets the ground mirror created by the helper.
  90844. */
  90845. get: function () {
  90846. return this._groundMirror;
  90847. },
  90848. enumerable: true,
  90849. configurable: true
  90850. });
  90851. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  90852. /**
  90853. * Gets the ground mirror render list to helps pushing the meshes
  90854. * you wish in the ground reflection.
  90855. */
  90856. get: function () {
  90857. if (this._groundMirror) {
  90858. return this._groundMirror.renderList;
  90859. }
  90860. return null;
  90861. },
  90862. enumerable: true,
  90863. configurable: true
  90864. });
  90865. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  90866. /**
  90867. * Gets the ground material created by the helper.
  90868. */
  90869. get: function () {
  90870. return this._groundMaterial;
  90871. },
  90872. enumerable: true,
  90873. configurable: true
  90874. });
  90875. /**
  90876. * Updates the background according to the new options
  90877. * @param options
  90878. */
  90879. EnvironmentHelper.prototype.updateOptions = function (options) {
  90880. var newOptions = __assign({}, this._options, options);
  90881. if (this._ground && !newOptions.createGround) {
  90882. this._ground.dispose();
  90883. this._ground = null;
  90884. }
  90885. if (this._groundMaterial && !newOptions.createGround) {
  90886. this._groundMaterial.dispose();
  90887. this._groundMaterial = null;
  90888. }
  90889. if (this._groundTexture) {
  90890. if (this._options.groundTexture != newOptions.groundTexture) {
  90891. this._groundTexture.dispose();
  90892. this._groundTexture = null;
  90893. }
  90894. }
  90895. if (this._skybox && !newOptions.createSkybox) {
  90896. this._skybox.dispose();
  90897. this._skybox = null;
  90898. }
  90899. if (this._skyboxMaterial && !newOptions.createSkybox) {
  90900. this._skyboxMaterial.dispose();
  90901. this._skyboxMaterial = null;
  90902. }
  90903. if (this._skyboxTexture) {
  90904. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  90905. this._skyboxTexture.dispose();
  90906. this._skyboxTexture = null;
  90907. }
  90908. }
  90909. if (this._groundMirror && !newOptions.enableGroundMirror) {
  90910. this._groundMirror.dispose();
  90911. this._groundMirror = null;
  90912. }
  90913. if (this._scene.environmentTexture) {
  90914. if (this._options.environmentTexture != newOptions.environmentTexture) {
  90915. this._scene.environmentTexture.dispose();
  90916. }
  90917. }
  90918. this._options = newOptions;
  90919. this._setupBackground();
  90920. this._setupImageProcessing();
  90921. };
  90922. /**
  90923. * Sets the primary color of all the available elements.
  90924. * @param color
  90925. */
  90926. EnvironmentHelper.prototype.setMainColor = function (color) {
  90927. if (this.groundMaterial) {
  90928. this.groundMaterial.primaryColor = color;
  90929. }
  90930. if (this.skyboxMaterial) {
  90931. this.skyboxMaterial.primaryColor = color;
  90932. }
  90933. if (this.groundMirror) {
  90934. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  90935. }
  90936. };
  90937. /**
  90938. * Setup the image processing according to the specified options.
  90939. */
  90940. EnvironmentHelper.prototype._setupImageProcessing = function () {
  90941. if (this._options.setupImageProcessing) {
  90942. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  90943. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  90944. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  90945. this._setupEnvironmentTexture();
  90946. }
  90947. };
  90948. /**
  90949. * Setup the environment texture according to the specified options.
  90950. */
  90951. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  90952. if (this._scene.environmentTexture) {
  90953. return;
  90954. }
  90955. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  90956. this._scene.environmentTexture = this._options.environmentTexture;
  90957. return;
  90958. }
  90959. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  90960. this._scene.environmentTexture = environmentTexture;
  90961. };
  90962. /**
  90963. * Setup the background according to the specified options.
  90964. */
  90965. EnvironmentHelper.prototype._setupBackground = function () {
  90966. if (!this._rootMesh) {
  90967. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  90968. }
  90969. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  90970. var sceneSize = this._getSceneSize();
  90971. if (this._options.createGround) {
  90972. this._setupGround(sceneSize);
  90973. this._setupGroundMaterial();
  90974. this._setupGroundDiffuseTexture();
  90975. if (this._options.enableGroundMirror) {
  90976. this._setupGroundMirrorTexture(sceneSize);
  90977. }
  90978. this._setupMirrorInGroundMaterial();
  90979. }
  90980. if (this._options.createSkybox) {
  90981. this._setupSkybox(sceneSize);
  90982. this._setupSkyboxMaterial();
  90983. this._setupSkyboxReflectionTexture();
  90984. }
  90985. this._rootMesh.position.x = sceneSize.rootPosition.x;
  90986. this._rootMesh.position.z = sceneSize.rootPosition.z;
  90987. this._rootMesh.position.y = sceneSize.rootPosition.y;
  90988. };
  90989. /**
  90990. * Get the scene sizes according to the setup.
  90991. */
  90992. EnvironmentHelper.prototype._getSceneSize = function () {
  90993. var _this = this;
  90994. var groundSize = this._options.groundSize;
  90995. var skyboxSize = this._options.skyboxSize;
  90996. var rootPosition = this._options.rootPosition;
  90997. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  90998. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  90999. }
  91000. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  91001. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  91002. });
  91003. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  91004. if (this._options.sizeAuto) {
  91005. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  91006. this._scene.activeCamera.upperRadiusLimit) {
  91007. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  91008. skyboxSize = groundSize;
  91009. }
  91010. var sceneDiagonalLenght = sceneDiagonal.length();
  91011. if (sceneDiagonalLenght > groundSize) {
  91012. groundSize = sceneDiagonalLenght * 2;
  91013. skyboxSize = groundSize;
  91014. }
  91015. // 10 % bigger.
  91016. groundSize *= 1.1;
  91017. skyboxSize *= 1.5;
  91018. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  91019. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  91020. }
  91021. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  91022. };
  91023. /**
  91024. * Setup the ground according to the specified options.
  91025. */
  91026. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  91027. var _this = this;
  91028. if (!this._ground) {
  91029. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  91030. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  91031. this._ground.parent = this._rootMesh;
  91032. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  91033. }
  91034. this._ground.receiveShadows = this._options.enableGroundShadow;
  91035. };
  91036. /**
  91037. * Setup the ground material according to the specified options.
  91038. */
  91039. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  91040. if (!this._groundMaterial) {
  91041. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  91042. }
  91043. this._groundMaterial.alpha = this._options.groundOpacity;
  91044. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  91045. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  91046. this._groundMaterial.primaryLevel = 1;
  91047. this._groundMaterial.primaryColor = this._options.groundColor;
  91048. this._groundMaterial.secondaryLevel = 0;
  91049. this._groundMaterial.tertiaryLevel = 0;
  91050. this._groundMaterial.useRGBColor = false;
  91051. this._groundMaterial.enableNoise = true;
  91052. if (this._ground) {
  91053. this._ground.material = this._groundMaterial;
  91054. }
  91055. };
  91056. /**
  91057. * Setup the ground diffuse texture according to the specified options.
  91058. */
  91059. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  91060. if (!this._groundMaterial) {
  91061. return;
  91062. }
  91063. if (this._groundTexture) {
  91064. return;
  91065. }
  91066. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  91067. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  91068. return;
  91069. }
  91070. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  91071. diffuseTexture.gammaSpace = false;
  91072. diffuseTexture.hasAlpha = true;
  91073. this._groundMaterial.diffuseTexture = diffuseTexture;
  91074. };
  91075. /**
  91076. * Setup the ground mirror texture according to the specified options.
  91077. */
  91078. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  91079. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91080. if (!this._groundMirror) {
  91081. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  91082. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  91083. this._groundMirror.anisotropicFilteringLevel = 1;
  91084. this._groundMirror.wrapU = wrapping;
  91085. this._groundMirror.wrapV = wrapping;
  91086. this._groundMirror.gammaSpace = false;
  91087. if (this._groundMirror.renderList) {
  91088. for (var i = 0; i < this._scene.meshes.length; i++) {
  91089. var mesh = this._scene.meshes[i];
  91090. if (mesh !== this._ground &&
  91091. mesh !== this._skybox &&
  91092. mesh !== this._rootMesh) {
  91093. this._groundMirror.renderList.push(mesh);
  91094. }
  91095. }
  91096. }
  91097. }
  91098. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  91099. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  91100. };
  91101. /**
  91102. * Setup the ground to receive the mirror texture.
  91103. */
  91104. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  91105. if (this._groundMaterial) {
  91106. this._groundMaterial.reflectionTexture = this._groundMirror;
  91107. this._groundMaterial.reflectionFresnel = true;
  91108. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  91109. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  91110. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  91111. }
  91112. };
  91113. /**
  91114. * Setup the skybox according to the specified options.
  91115. */
  91116. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  91117. var _this = this;
  91118. if (!this._skybox) {
  91119. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  91120. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  91121. }
  91122. this._skybox.parent = this._rootMesh;
  91123. };
  91124. /**
  91125. * Setup the skybox material according to the specified options.
  91126. */
  91127. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  91128. if (!this._skybox) {
  91129. return;
  91130. }
  91131. if (!this._skyboxMaterial) {
  91132. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  91133. }
  91134. this._skyboxMaterial.useRGBColor = false;
  91135. this._skyboxMaterial.primaryLevel = 1;
  91136. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  91137. this._skyboxMaterial.secondaryLevel = 0;
  91138. this._skyboxMaterial.tertiaryLevel = 0;
  91139. this._skyboxMaterial.enableNoise = true;
  91140. this._skybox.material = this._skyboxMaterial;
  91141. };
  91142. /**
  91143. * Setup the skybox reflection texture according to the specified options.
  91144. */
  91145. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  91146. if (!this._skyboxMaterial) {
  91147. return;
  91148. }
  91149. if (this._skyboxTexture) {
  91150. return;
  91151. }
  91152. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  91153. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  91154. return;
  91155. }
  91156. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  91157. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  91158. this._skyboxTexture.gammaSpace = false;
  91159. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  91160. };
  91161. /**
  91162. * Dispose all the elements created by the Helper.
  91163. */
  91164. EnvironmentHelper.prototype.dispose = function () {
  91165. if (this._groundMaterial) {
  91166. this._groundMaterial.dispose(true, true);
  91167. }
  91168. if (this._skyboxMaterial) {
  91169. this._skyboxMaterial.dispose(true, true);
  91170. }
  91171. this._rootMesh.dispose(false);
  91172. };
  91173. /**
  91174. * Default ground texture URL.
  91175. */
  91176. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  91177. /**
  91178. * Default skybox texture URL.
  91179. */
  91180. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  91181. /**
  91182. * Default environment texture URL.
  91183. */
  91184. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  91185. return EnvironmentHelper;
  91186. }());
  91187. BABYLON.EnvironmentHelper = EnvironmentHelper;
  91188. })(BABYLON || (BABYLON = {}));
  91189. //# sourceMappingURL=babylon.environmentHelper.js.map
  91190. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb);\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=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\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\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#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\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\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\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\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#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 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{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\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 vec3 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.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","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}","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\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{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(textureSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\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","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\n#ifdef GRAIN\nvec2 seed=vUV*(grainAnimatedSeed);\nfloat grain=dither(seed,grainVarianceAmount);\n\nfloat lum=getLuminance(result.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\nresult.rgb+=grain*grainAmount;\nresult.rgb=max(result.rgb,0.0);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","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#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\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{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifndef GRAIN \n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\n#endif\ngl_FragColor=color;\n}\n"};
  91191. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\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};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\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 computeShadowWithPoissonSamplingCube(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 computeShadowWithPoissonSampling(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#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif\n#ifdef GRAIN\nuniform float grainVarianceAmount;\nuniform float grainAnimatedSeed;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(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#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,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#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}","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};","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","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};"};
  91192. "use strict";
  91193. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  91194. var BABYLON;
  91195. (function (BABYLON) {
  91196. var GridMaterialDefines = /** @class */ (function (_super) {
  91197. __extends(GridMaterialDefines, _super);
  91198. function GridMaterialDefines() {
  91199. var _this = _super.call(this) || this;
  91200. _this.TRANSPARENT = false;
  91201. _this.FOG = false;
  91202. _this.PREMULTIPLYALPHA = false;
  91203. _this.rebuild();
  91204. return _this;
  91205. }
  91206. return GridMaterialDefines;
  91207. }(BABYLON.MaterialDefines));
  91208. /**
  91209. * The grid materials allows you to wrap any shape with a grid.
  91210. * Colors are customizable.
  91211. */
  91212. var GridMaterial = /** @class */ (function (_super) {
  91213. __extends(GridMaterial, _super);
  91214. /**
  91215. * constructor
  91216. * @param name The name given to the material in order to identify it afterwards.
  91217. * @param scene The scene the material is used in.
  91218. */
  91219. function GridMaterial(name, scene) {
  91220. var _this = _super.call(this, name, scene) || this;
  91221. /**
  91222. * Main color of the grid (e.g. between lines)
  91223. */
  91224. _this.mainColor = BABYLON.Color3.Black();
  91225. /**
  91226. * Color of the grid lines.
  91227. */
  91228. _this.lineColor = BABYLON.Color3.Teal();
  91229. /**
  91230. * The scale of the grid compared to unit.
  91231. */
  91232. _this.gridRatio = 1.0;
  91233. /**
  91234. * Allows setting an offset for the grid lines.
  91235. */
  91236. _this.gridOffset = BABYLON.Vector3.Zero();
  91237. /**
  91238. * The frequency of thicker lines.
  91239. */
  91240. _this.majorUnitFrequency = 10;
  91241. /**
  91242. * The visibility of minor units in the grid.
  91243. */
  91244. _this.minorUnitVisibility = 0.33;
  91245. /**
  91246. * The grid opacity outside of the lines.
  91247. */
  91248. _this.opacity = 1.0;
  91249. /**
  91250. * Determine RBG output is premultiplied by alpha value.
  91251. */
  91252. _this.preMultiplyAlpha = false;
  91253. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  91254. return _this;
  91255. }
  91256. /**
  91257. * Returns wehter or not the grid requires alpha blending.
  91258. */
  91259. GridMaterial.prototype.needAlphaBlending = function () {
  91260. return this.opacity < 1.0;
  91261. };
  91262. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  91263. return this.needAlphaBlending();
  91264. };
  91265. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  91266. if (this.isFrozen) {
  91267. if (this._wasPreviouslyReady && subMesh.effect) {
  91268. return true;
  91269. }
  91270. }
  91271. if (!subMesh._materialDefines) {
  91272. subMesh._materialDefines = new GridMaterialDefines();
  91273. }
  91274. var defines = subMesh._materialDefines;
  91275. var scene = this.getScene();
  91276. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  91277. if (this._renderId === scene.getRenderId()) {
  91278. return true;
  91279. }
  91280. }
  91281. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  91282. defines.TRANSPARENT = !defines.TRANSPARENT;
  91283. defines.markAsUnprocessed();
  91284. }
  91285. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  91286. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  91287. defines.markAsUnprocessed();
  91288. }
  91289. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, false, defines);
  91290. // Get correct effect
  91291. if (defines.isDirty) {
  91292. defines.markAsProcessed();
  91293. scene.resetCachedMaterial();
  91294. // Attributes
  91295. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  91296. // Defines
  91297. var join = defines.toString();
  91298. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  91299. }
  91300. if (!subMesh.effect || !subMesh.effect.isReady()) {
  91301. return false;
  91302. }
  91303. this._renderId = scene.getRenderId();
  91304. this._wasPreviouslyReady = true;
  91305. return true;
  91306. };
  91307. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  91308. var scene = this.getScene();
  91309. var defines = subMesh._materialDefines;
  91310. if (!defines) {
  91311. return;
  91312. }
  91313. var effect = subMesh.effect;
  91314. if (!effect) {
  91315. return;
  91316. }
  91317. this._activeEffect = effect;
  91318. // Matrices
  91319. this.bindOnlyWorldMatrix(world);
  91320. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  91321. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  91322. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  91323. // Uniforms
  91324. if (this._mustRebind(scene, effect)) {
  91325. this._activeEffect.setColor3("mainColor", this.mainColor);
  91326. this._activeEffect.setColor3("lineColor", this.lineColor);
  91327. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  91328. this._gridControl.x = this.gridRatio;
  91329. this._gridControl.y = Math.round(this.majorUnitFrequency);
  91330. this._gridControl.z = this.minorUnitVisibility;
  91331. this._gridControl.w = this.opacity;
  91332. this._activeEffect.setVector4("gridControl", this._gridControl);
  91333. }
  91334. // Fog
  91335. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  91336. this._afterBind(mesh, this._activeEffect);
  91337. };
  91338. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  91339. _super.prototype.dispose.call(this, forceDisposeEffect);
  91340. };
  91341. GridMaterial.prototype.clone = function (name) {
  91342. var _this = this;
  91343. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  91344. };
  91345. GridMaterial.prototype.serialize = function () {
  91346. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  91347. serializationObject.customType = "BABYLON.GridMaterial";
  91348. return serializationObject;
  91349. };
  91350. GridMaterial.prototype.getClassName = function () {
  91351. return "GridMaterial";
  91352. };
  91353. GridMaterial.Parse = function (source, scene, rootUrl) {
  91354. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  91355. };
  91356. __decorate([
  91357. BABYLON.serializeAsColor3()
  91358. ], GridMaterial.prototype, "mainColor", void 0);
  91359. __decorate([
  91360. BABYLON.serializeAsColor3()
  91361. ], GridMaterial.prototype, "lineColor", void 0);
  91362. __decorate([
  91363. BABYLON.serialize()
  91364. ], GridMaterial.prototype, "gridRatio", void 0);
  91365. __decorate([
  91366. BABYLON.serializeAsColor3()
  91367. ], GridMaterial.prototype, "gridOffset", void 0);
  91368. __decorate([
  91369. BABYLON.serialize()
  91370. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  91371. __decorate([
  91372. BABYLON.serialize()
  91373. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  91374. __decorate([
  91375. BABYLON.serialize()
  91376. ], GridMaterial.prototype, "opacity", void 0);
  91377. __decorate([
  91378. BABYLON.serialize()
  91379. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  91380. return GridMaterial;
  91381. }(BABYLON.PushMaterial));
  91382. BABYLON.GridMaterial = GridMaterial;
  91383. })(BABYLON || (BABYLON = {}));
  91384. //# sourceMappingURL=babylon.gridmaterial.js.map
  91385. 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}";
  91386. 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}";
  91387. "use strict";
  91388. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  91389. var BABYLON;
  91390. (function (BABYLON) {
  91391. var GLTFLoaderCoordinateSystemMode;
  91392. (function (GLTFLoaderCoordinateSystemMode) {
  91393. /**
  91394. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  91395. */
  91396. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  91397. /**
  91398. * Sets the useRightHandedSystem flag on the scene.
  91399. */
  91400. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  91401. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  91402. var GLTFLoaderAnimationStartMode;
  91403. (function (GLTFLoaderAnimationStartMode) {
  91404. /**
  91405. * No animation will start.
  91406. */
  91407. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  91408. /**
  91409. * The first animation will start.
  91410. */
  91411. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  91412. /**
  91413. * All animations will start.
  91414. */
  91415. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  91416. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  91417. var GLTFLoaderState;
  91418. (function (GLTFLoaderState) {
  91419. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  91420. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  91421. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  91422. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  91423. var GLTFFileLoader = /** @class */ (function () {
  91424. function GLTFFileLoader() {
  91425. // #region Common options
  91426. /**
  91427. * Raised when the asset has been parsed.
  91428. * The data.json property stores the glTF JSON.
  91429. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  91430. */
  91431. this.onParsedObservable = new BABYLON.Observable();
  91432. // #endregion
  91433. // #region V2 options
  91434. /**
  91435. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  91436. */
  91437. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  91438. /**
  91439. * The animation start mode (NONE, FIRST, ALL).
  91440. */
  91441. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  91442. /**
  91443. * Set to true to compile materials before raising the success callback.
  91444. */
  91445. this.compileMaterials = false;
  91446. /**
  91447. * Set to true to also compile materials with clip planes.
  91448. */
  91449. this.useClipPlane = false;
  91450. /**
  91451. * Set to true to compile shadow generators before raising the success callback.
  91452. */
  91453. this.compileShadowGenerators = false;
  91454. /**
  91455. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  91456. */
  91457. this.onMeshLoadedObservable = new BABYLON.Observable();
  91458. /**
  91459. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  91460. */
  91461. this.onTextureLoadedObservable = new BABYLON.Observable();
  91462. /**
  91463. * Raised when the loader creates a material after parsing the glTF properties of the material.
  91464. */
  91465. this.onMaterialLoadedObservable = new BABYLON.Observable();
  91466. /**
  91467. * Raised when the loader creates an animation group after parsing the glTF properties of the animation.
  91468. */
  91469. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  91470. /**
  91471. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  91472. * For assets with LODs, raised when all of the LODs are complete.
  91473. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  91474. */
  91475. this.onCompleteObservable = new BABYLON.Observable();
  91476. /**
  91477. * Raised when the loader is disposed.
  91478. */
  91479. this.onDisposeObservable = new BABYLON.Observable();
  91480. /**
  91481. * Raised after a loader extension is created.
  91482. * Set additional options for a loader extension in this event.
  91483. */
  91484. this.onExtensionLoadedObservable = new BABYLON.Observable();
  91485. // #endregion
  91486. this._loader = null;
  91487. this.name = "gltf";
  91488. this.extensions = {
  91489. ".gltf": { isBinary: false },
  91490. ".glb": { isBinary: true }
  91491. };
  91492. }
  91493. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  91494. set: function (callback) {
  91495. if (this._onParsedObserver) {
  91496. this.onParsedObservable.remove(this._onParsedObserver);
  91497. }
  91498. this._onParsedObserver = this.onParsedObservable.add(callback);
  91499. },
  91500. enumerable: true,
  91501. configurable: true
  91502. });
  91503. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  91504. set: function (callback) {
  91505. if (this._onMeshLoadedObserver) {
  91506. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  91507. }
  91508. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  91509. },
  91510. enumerable: true,
  91511. configurable: true
  91512. });
  91513. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  91514. set: function (callback) {
  91515. if (this._onTextureLoadedObserver) {
  91516. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  91517. }
  91518. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  91519. },
  91520. enumerable: true,
  91521. configurable: true
  91522. });
  91523. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  91524. set: function (callback) {
  91525. if (this._onMaterialLoadedObserver) {
  91526. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  91527. }
  91528. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  91529. },
  91530. enumerable: true,
  91531. configurable: true
  91532. });
  91533. Object.defineProperty(GLTFFileLoader.prototype, "onAnimationGroupLoaded", {
  91534. set: function (callback) {
  91535. if (this._onAnimationGroupLoadedObserver) {
  91536. this.onAnimationGroupLoadedObservable.remove(this._onAnimationGroupLoadedObserver);
  91537. }
  91538. this._onAnimationGroupLoadedObserver = this.onAnimationGroupLoadedObservable.add(callback);
  91539. },
  91540. enumerable: true,
  91541. configurable: true
  91542. });
  91543. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  91544. set: function (callback) {
  91545. if (this._onCompleteObserver) {
  91546. this.onCompleteObservable.remove(this._onCompleteObserver);
  91547. }
  91548. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  91549. },
  91550. enumerable: true,
  91551. configurable: true
  91552. });
  91553. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  91554. set: function (callback) {
  91555. if (this._onDisposeObserver) {
  91556. this.onDisposeObservable.remove(this._onDisposeObserver);
  91557. }
  91558. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  91559. },
  91560. enumerable: true,
  91561. configurable: true
  91562. });
  91563. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  91564. set: function (callback) {
  91565. if (this._onExtensionLoadedObserver) {
  91566. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  91567. }
  91568. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  91569. },
  91570. enumerable: true,
  91571. configurable: true
  91572. });
  91573. /**
  91574. * Gets a promise that resolves when the asset is completely loaded.
  91575. * @returns A promise that resolves when the asset is completely loaded.
  91576. */
  91577. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  91578. var _this = this;
  91579. return new Promise(function (resolve) {
  91580. _this.onCompleteObservable.add(function () {
  91581. resolve();
  91582. }, undefined, undefined, undefined, true);
  91583. });
  91584. };
  91585. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  91586. /**
  91587. * The loader state or null if not active.
  91588. */
  91589. get: function () {
  91590. return this._loader ? this._loader.state : null;
  91591. },
  91592. enumerable: true,
  91593. configurable: true
  91594. });
  91595. /**
  91596. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  91597. */
  91598. GLTFFileLoader.prototype.dispose = function () {
  91599. if (this._loader) {
  91600. this._loader.dispose();
  91601. this._loader = null;
  91602. }
  91603. this.onMeshLoadedObservable.clear();
  91604. this.onTextureLoadedObservable.clear();
  91605. this.onMaterialLoadedObservable.clear();
  91606. this.onDisposeObservable.notifyObservers(this);
  91607. this.onDisposeObservable.clear();
  91608. };
  91609. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  91610. var _this = this;
  91611. return Promise.resolve().then(function () {
  91612. var loaderData = _this._parse(data);
  91613. _this._loader = _this._getLoader(loaderData);
  91614. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  91615. });
  91616. };
  91617. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  91618. var _this = this;
  91619. return Promise.resolve().then(function () {
  91620. var loaderData = _this._parse(data);
  91621. _this._loader = _this._getLoader(loaderData);
  91622. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  91623. });
  91624. };
  91625. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  91626. var _this = this;
  91627. return Promise.resolve().then(function () {
  91628. var loaderData = _this._parse(data);
  91629. _this._loader = _this._getLoader(loaderData);
  91630. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  91631. var container = new BABYLON.AssetContainer(scene);
  91632. Array.prototype.push.apply(container.meshes, result.meshes);
  91633. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  91634. Array.prototype.push.apply(container.skeletons, result.skeletons);
  91635. container.removeAllFromScene();
  91636. return container;
  91637. });
  91638. });
  91639. };
  91640. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  91641. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  91642. };
  91643. GLTFFileLoader.prototype.createPlugin = function () {
  91644. return new GLTFFileLoader();
  91645. };
  91646. GLTFFileLoader.prototype._parse = function (data) {
  91647. var parsedData;
  91648. if (data instanceof ArrayBuffer) {
  91649. parsedData = GLTFFileLoader._parseBinary(data);
  91650. }
  91651. else {
  91652. parsedData = {
  91653. json: JSON.parse(data),
  91654. bin: null
  91655. };
  91656. }
  91657. this.onParsedObservable.notifyObservers(parsedData);
  91658. this.onParsedObservable.clear();
  91659. return parsedData;
  91660. };
  91661. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  91662. var _this = this;
  91663. var loaderVersion = { major: 2, minor: 0 };
  91664. var asset = loaderData.json.asset || {};
  91665. var version = GLTFFileLoader._parseVersion(asset.version);
  91666. if (!version) {
  91667. throw new Error("Invalid version: " + asset.version);
  91668. }
  91669. if (asset.minVersion !== undefined) {
  91670. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  91671. if (!minVersion) {
  91672. throw new Error("Invalid minimum version: " + asset.minVersion);
  91673. }
  91674. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  91675. throw new Error("Incompatible minimum version: " + asset.minVersion);
  91676. }
  91677. }
  91678. var createLoaders = {
  91679. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  91680. 2: GLTFFileLoader.CreateGLTFLoaderV2
  91681. };
  91682. var createLoader = createLoaders[version.major];
  91683. if (!createLoader) {
  91684. throw new Error("Unsupported version: " + asset.version);
  91685. }
  91686. var loader = createLoader();
  91687. loader.coordinateSystemMode = this.coordinateSystemMode;
  91688. loader.animationStartMode = this.animationStartMode;
  91689. loader.compileMaterials = this.compileMaterials;
  91690. loader.useClipPlane = this.useClipPlane;
  91691. loader.compileShadowGenerators = this.compileShadowGenerators;
  91692. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  91693. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  91694. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  91695. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  91696. loader.onAnimationGroupLoadedObservable.add(function (animationGroup) { return _this.onAnimationGroupLoadedObservable.notifyObservers(animationGroup); });
  91697. loader.onCompleteObservable.add(function () {
  91698. _this.onMeshLoadedObservable.clear();
  91699. _this.onTextureLoadedObservable.clear();
  91700. _this.onMaterialLoadedObservable.clear();
  91701. _this.onCompleteObservable.notifyObservers(_this);
  91702. _this.onCompleteObservable.clear();
  91703. });
  91704. return loader;
  91705. };
  91706. GLTFFileLoader._parseBinary = function (data) {
  91707. var Binary = {
  91708. Magic: 0x46546C67
  91709. };
  91710. var binaryReader = new BinaryReader(data);
  91711. var magic = binaryReader.readUint32();
  91712. if (magic !== Binary.Magic) {
  91713. throw new Error("Unexpected magic: " + magic);
  91714. }
  91715. var version = binaryReader.readUint32();
  91716. switch (version) {
  91717. case 1: return GLTFFileLoader._parseV1(binaryReader);
  91718. case 2: return GLTFFileLoader._parseV2(binaryReader);
  91719. }
  91720. throw new Error("Unsupported version: " + version);
  91721. };
  91722. GLTFFileLoader._parseV1 = function (binaryReader) {
  91723. var ContentFormat = {
  91724. JSON: 0
  91725. };
  91726. var length = binaryReader.readUint32();
  91727. if (length != binaryReader.getLength()) {
  91728. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  91729. }
  91730. var contentLength = binaryReader.readUint32();
  91731. var contentFormat = binaryReader.readUint32();
  91732. var content;
  91733. switch (contentFormat) {
  91734. case ContentFormat.JSON: {
  91735. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  91736. break;
  91737. }
  91738. default: {
  91739. throw new Error("Unexpected content format: " + contentFormat);
  91740. }
  91741. }
  91742. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  91743. var body = binaryReader.readUint8Array(bytesRemaining);
  91744. return {
  91745. json: content,
  91746. bin: body
  91747. };
  91748. };
  91749. GLTFFileLoader._parseV2 = function (binaryReader) {
  91750. var ChunkFormat = {
  91751. JSON: 0x4E4F534A,
  91752. BIN: 0x004E4942
  91753. };
  91754. var length = binaryReader.readUint32();
  91755. if (length !== binaryReader.getLength()) {
  91756. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  91757. }
  91758. // JSON chunk
  91759. var chunkLength = binaryReader.readUint32();
  91760. var chunkFormat = binaryReader.readUint32();
  91761. if (chunkFormat !== ChunkFormat.JSON) {
  91762. throw new Error("First chunk format is not JSON");
  91763. }
  91764. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  91765. // Look for BIN chunk
  91766. var bin = null;
  91767. while (binaryReader.getPosition() < binaryReader.getLength()) {
  91768. var chunkLength_1 = binaryReader.readUint32();
  91769. var chunkFormat_1 = binaryReader.readUint32();
  91770. switch (chunkFormat_1) {
  91771. case ChunkFormat.JSON: {
  91772. throw new Error("Unexpected JSON chunk");
  91773. }
  91774. case ChunkFormat.BIN: {
  91775. bin = binaryReader.readUint8Array(chunkLength_1);
  91776. break;
  91777. }
  91778. default: {
  91779. // ignore unrecognized chunkFormat
  91780. binaryReader.skipBytes(chunkLength_1);
  91781. break;
  91782. }
  91783. }
  91784. }
  91785. return {
  91786. json: json,
  91787. bin: bin
  91788. };
  91789. };
  91790. GLTFFileLoader._parseVersion = function (version) {
  91791. if (version === "1.0" || version === "1.0.1") {
  91792. return {
  91793. major: 1,
  91794. minor: 0
  91795. };
  91796. }
  91797. var match = (version + "").match(/^(\d+)\.(\d+)/);
  91798. if (!match) {
  91799. return null;
  91800. }
  91801. return {
  91802. major: parseInt(match[1]),
  91803. minor: parseInt(match[2])
  91804. };
  91805. };
  91806. GLTFFileLoader._compareVersion = function (a, b) {
  91807. if (a.major > b.major)
  91808. return 1;
  91809. if (a.major < b.major)
  91810. return -1;
  91811. if (a.minor > b.minor)
  91812. return 1;
  91813. if (a.minor < b.minor)
  91814. return -1;
  91815. return 0;
  91816. };
  91817. GLTFFileLoader._decodeBufferToText = function (buffer) {
  91818. var result = "";
  91819. var length = buffer.byteLength;
  91820. for (var i = 0; i < length; i++) {
  91821. result += String.fromCharCode(buffer[i]);
  91822. }
  91823. return result;
  91824. };
  91825. // #endregion
  91826. // #region V1 options
  91827. GLTFFileLoader.IncrementalLoading = true;
  91828. GLTFFileLoader.HomogeneousCoordinates = false;
  91829. return GLTFFileLoader;
  91830. }());
  91831. BABYLON.GLTFFileLoader = GLTFFileLoader;
  91832. var BinaryReader = /** @class */ (function () {
  91833. function BinaryReader(arrayBuffer) {
  91834. this._arrayBuffer = arrayBuffer;
  91835. this._dataView = new DataView(arrayBuffer);
  91836. this._byteOffset = 0;
  91837. }
  91838. BinaryReader.prototype.getPosition = function () {
  91839. return this._byteOffset;
  91840. };
  91841. BinaryReader.prototype.getLength = function () {
  91842. return this._arrayBuffer.byteLength;
  91843. };
  91844. BinaryReader.prototype.readUint32 = function () {
  91845. var value = this._dataView.getUint32(this._byteOffset, true);
  91846. this._byteOffset += 4;
  91847. return value;
  91848. };
  91849. BinaryReader.prototype.readUint8Array = function (length) {
  91850. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  91851. this._byteOffset += length;
  91852. return value;
  91853. };
  91854. BinaryReader.prototype.skipBytes = function (length) {
  91855. this._byteOffset += length;
  91856. };
  91857. return BinaryReader;
  91858. }());
  91859. if (BABYLON.SceneLoader) {
  91860. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  91861. }
  91862. })(BABYLON || (BABYLON = {}));
  91863. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  91864. "use strict";
  91865. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  91866. var BABYLON;
  91867. (function (BABYLON) {
  91868. var GLTF1;
  91869. (function (GLTF1) {
  91870. /**
  91871. * Enums
  91872. */
  91873. var EComponentType;
  91874. (function (EComponentType) {
  91875. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  91876. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  91877. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  91878. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  91879. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  91880. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  91881. var EShaderType;
  91882. (function (EShaderType) {
  91883. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  91884. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  91885. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  91886. var EParameterType;
  91887. (function (EParameterType) {
  91888. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  91889. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  91890. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  91891. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  91892. EParameterType[EParameterType["INT"] = 5124] = "INT";
  91893. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  91894. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  91895. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  91896. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  91897. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  91898. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  91899. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  91900. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  91901. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  91902. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  91903. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  91904. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  91905. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  91906. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  91907. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  91908. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  91909. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  91910. var ETextureWrapMode;
  91911. (function (ETextureWrapMode) {
  91912. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  91913. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  91914. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  91915. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  91916. var ETextureFilterType;
  91917. (function (ETextureFilterType) {
  91918. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  91919. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  91920. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  91921. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  91922. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  91923. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  91924. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  91925. var ETextureFormat;
  91926. (function (ETextureFormat) {
  91927. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  91928. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  91929. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  91930. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  91931. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  91932. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  91933. var ECullingType;
  91934. (function (ECullingType) {
  91935. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  91936. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  91937. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  91938. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  91939. var EBlendingFunction;
  91940. (function (EBlendingFunction) {
  91941. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  91942. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  91943. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  91944. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  91945. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  91946. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  91947. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  91948. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  91949. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  91950. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  91951. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  91952. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  91953. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  91954. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  91955. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  91956. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  91957. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  91958. })(BABYLON || (BABYLON = {}));
  91959. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  91960. "use strict";
  91961. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  91962. var BABYLON;
  91963. (function (BABYLON) {
  91964. var GLTF1;
  91965. (function (GLTF1) {
  91966. /**
  91967. * Tokenizer. Used for shaders compatibility
  91968. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  91969. */
  91970. var ETokenType;
  91971. (function (ETokenType) {
  91972. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  91973. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  91974. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  91975. })(ETokenType || (ETokenType = {}));
  91976. var Tokenizer = /** @class */ (function () {
  91977. function Tokenizer(toParse) {
  91978. this._pos = 0;
  91979. this.currentToken = ETokenType.UNKNOWN;
  91980. this.currentIdentifier = "";
  91981. this.currentString = "";
  91982. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  91983. this._toParse = toParse;
  91984. this._maxPos = toParse.length;
  91985. }
  91986. Tokenizer.prototype.getNextToken = function () {
  91987. if (this.isEnd())
  91988. return ETokenType.END_OF_INPUT;
  91989. this.currentString = this.read();
  91990. this.currentToken = ETokenType.UNKNOWN;
  91991. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  91992. this.currentToken = ETokenType.IDENTIFIER;
  91993. this.currentIdentifier = this.currentString;
  91994. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  91995. this.currentIdentifier += this.currentString;
  91996. this.forward();
  91997. }
  91998. }
  91999. return this.currentToken;
  92000. };
  92001. Tokenizer.prototype.peek = function () {
  92002. return this._toParse[this._pos];
  92003. };
  92004. Tokenizer.prototype.read = function () {
  92005. return this._toParse[this._pos++];
  92006. };
  92007. Tokenizer.prototype.forward = function () {
  92008. this._pos++;
  92009. };
  92010. Tokenizer.prototype.isEnd = function () {
  92011. return this._pos >= this._maxPos;
  92012. };
  92013. return Tokenizer;
  92014. }());
  92015. /**
  92016. * Values
  92017. */
  92018. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  92019. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  92020. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  92021. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  92022. /**
  92023. * Parse
  92024. */
  92025. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  92026. for (var buf in parsedBuffers) {
  92027. var parsedBuffer = parsedBuffers[buf];
  92028. gltfRuntime.buffers[buf] = parsedBuffer;
  92029. gltfRuntime.buffersCount++;
  92030. }
  92031. };
  92032. var parseShaders = function (parsedShaders, gltfRuntime) {
  92033. for (var sha in parsedShaders) {
  92034. var parsedShader = parsedShaders[sha];
  92035. gltfRuntime.shaders[sha] = parsedShader;
  92036. gltfRuntime.shaderscount++;
  92037. }
  92038. };
  92039. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  92040. for (var object in parsedObjects) {
  92041. var parsedObject = parsedObjects[object];
  92042. gltfRuntime[runtimeProperty][object] = parsedObject;
  92043. }
  92044. };
  92045. /**
  92046. * Utils
  92047. */
  92048. var normalizeUVs = function (buffer) {
  92049. if (!buffer) {
  92050. return;
  92051. }
  92052. for (var i = 0; i < buffer.length / 2; i++) {
  92053. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  92054. }
  92055. };
  92056. var getAttribute = function (attributeParameter) {
  92057. if (attributeParameter.semantic === "NORMAL") {
  92058. return "normal";
  92059. }
  92060. else if (attributeParameter.semantic === "POSITION") {
  92061. return "position";
  92062. }
  92063. else if (attributeParameter.semantic === "JOINT") {
  92064. return "matricesIndices";
  92065. }
  92066. else if (attributeParameter.semantic === "WEIGHT") {
  92067. return "matricesWeights";
  92068. }
  92069. else if (attributeParameter.semantic === "COLOR") {
  92070. return "color";
  92071. }
  92072. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  92073. var channel = Number(attributeParameter.semantic.split("_")[1]);
  92074. return "uv" + (channel === 0 ? "" : channel + 1);
  92075. }
  92076. return null;
  92077. };
  92078. /**
  92079. * Loads and creates animations
  92080. */
  92081. var loadAnimations = function (gltfRuntime) {
  92082. for (var anim in gltfRuntime.animations) {
  92083. var animation = gltfRuntime.animations[anim];
  92084. if (!animation.channels || !animation.samplers) {
  92085. continue;
  92086. }
  92087. var lastAnimation = null;
  92088. for (var i = 0; i < animation.channels.length; i++) {
  92089. // Get parameters and load buffers
  92090. var channel = animation.channels[i];
  92091. var sampler = animation.samplers[channel.sampler];
  92092. if (!sampler) {
  92093. continue;
  92094. }
  92095. var inputData = null;
  92096. var outputData = null;
  92097. if (animation.parameters) {
  92098. inputData = animation.parameters[sampler.input];
  92099. outputData = animation.parameters[sampler.output];
  92100. }
  92101. else {
  92102. inputData = sampler.input;
  92103. outputData = sampler.output;
  92104. }
  92105. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  92106. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  92107. var targetID = channel.target.id;
  92108. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  92109. if (targetNode === null) {
  92110. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  92111. }
  92112. if (targetNode === null) {
  92113. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  92114. continue;
  92115. }
  92116. var isBone = targetNode instanceof BABYLON.Bone;
  92117. // Get target path (position, rotation or scaling)
  92118. var targetPath = channel.target.path;
  92119. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  92120. if (targetPathIndex !== -1) {
  92121. targetPath = babylonAnimationPaths[targetPathIndex];
  92122. }
  92123. // Determine animation type
  92124. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  92125. if (!isBone) {
  92126. if (targetPath === "rotationQuaternion") {
  92127. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  92128. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  92129. }
  92130. else {
  92131. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  92132. }
  92133. }
  92134. // Create animation and key frames
  92135. var babylonAnimation = null;
  92136. var keys = [];
  92137. var arrayOffset = 0;
  92138. var modifyKey = false;
  92139. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  92140. babylonAnimation = lastAnimation;
  92141. modifyKey = true;
  92142. }
  92143. if (!modifyKey) {
  92144. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  92145. }
  92146. // For each frame
  92147. for (var j = 0; j < bufferInput.length; j++) {
  92148. var value = null;
  92149. if (targetPath === "rotationQuaternion") {
  92150. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  92151. arrayOffset += 4;
  92152. }
  92153. else {
  92154. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  92155. arrayOffset += 3;
  92156. }
  92157. if (isBone) {
  92158. var bone = targetNode;
  92159. var translation = BABYLON.Vector3.Zero();
  92160. var rotationQuaternion = new BABYLON.Quaternion();
  92161. var scaling = BABYLON.Vector3.Zero();
  92162. // Warning on decompose
  92163. var mat = bone.getBaseMatrix();
  92164. if (modifyKey && lastAnimation) {
  92165. mat = lastAnimation.getKeys()[j].value;
  92166. }
  92167. mat.decompose(scaling, rotationQuaternion, translation);
  92168. if (targetPath === "position") {
  92169. translation = value;
  92170. }
  92171. else if (targetPath === "rotationQuaternion") {
  92172. rotationQuaternion = value;
  92173. }
  92174. else {
  92175. scaling = value;
  92176. }
  92177. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  92178. }
  92179. if (!modifyKey) {
  92180. keys.push({
  92181. frame: bufferInput[j],
  92182. value: value
  92183. });
  92184. }
  92185. else if (lastAnimation) {
  92186. lastAnimation.getKeys()[j].value = value;
  92187. }
  92188. }
  92189. // Finish
  92190. if (!modifyKey && babylonAnimation) {
  92191. babylonAnimation.setKeys(keys);
  92192. targetNode.animations.push(babylonAnimation);
  92193. }
  92194. lastAnimation = babylonAnimation;
  92195. gltfRuntime.scene.stopAnimation(targetNode);
  92196. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  92197. }
  92198. }
  92199. };
  92200. /**
  92201. * Returns the bones transformation matrix
  92202. */
  92203. var configureBoneTransformation = function (node) {
  92204. var mat = null;
  92205. if (node.translation || node.rotation || node.scale) {
  92206. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  92207. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  92208. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  92209. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  92210. }
  92211. else {
  92212. mat = BABYLON.Matrix.FromArray(node.matrix);
  92213. }
  92214. return mat;
  92215. };
  92216. /**
  92217. * Returns the parent bone
  92218. */
  92219. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  92220. // Try to find
  92221. for (var i = 0; i < newSkeleton.bones.length; i++) {
  92222. if (newSkeleton.bones[i].name === jointName) {
  92223. return newSkeleton.bones[i];
  92224. }
  92225. }
  92226. // Not found, search in gltf nodes
  92227. var nodes = gltfRuntime.nodes;
  92228. for (var nde in nodes) {
  92229. var node = nodes[nde];
  92230. if (!node.jointName) {
  92231. continue;
  92232. }
  92233. var children = node.children;
  92234. for (var i = 0; i < children.length; i++) {
  92235. var child = gltfRuntime.nodes[children[i]];
  92236. if (!child.jointName) {
  92237. continue;
  92238. }
  92239. if (child.jointName === jointName) {
  92240. var mat = configureBoneTransformation(node);
  92241. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  92242. bone.id = nde;
  92243. return bone;
  92244. }
  92245. }
  92246. }
  92247. return null;
  92248. };
  92249. /**
  92250. * Returns the appropriate root node
  92251. */
  92252. var getNodeToRoot = function (nodesToRoot, id) {
  92253. for (var i = 0; i < nodesToRoot.length; i++) {
  92254. var nodeToRoot = nodesToRoot[i];
  92255. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  92256. var child = nodeToRoot.node.children[j];
  92257. if (child === id) {
  92258. return nodeToRoot.bone;
  92259. }
  92260. }
  92261. }
  92262. return null;
  92263. };
  92264. /**
  92265. * Returns the node with the joint name
  92266. */
  92267. var getJointNode = function (gltfRuntime, jointName) {
  92268. var nodes = gltfRuntime.nodes;
  92269. var node = nodes[jointName];
  92270. if (node) {
  92271. return {
  92272. node: node,
  92273. id: jointName
  92274. };
  92275. }
  92276. for (var nde in nodes) {
  92277. node = nodes[nde];
  92278. if (node.jointName === jointName) {
  92279. return {
  92280. node: node,
  92281. id: nde
  92282. };
  92283. }
  92284. }
  92285. return null;
  92286. };
  92287. /**
  92288. * Checks if a nodes is in joints
  92289. */
  92290. var nodeIsInJoints = function (skins, id) {
  92291. for (var i = 0; i < skins.jointNames.length; i++) {
  92292. if (skins.jointNames[i] === id) {
  92293. return true;
  92294. }
  92295. }
  92296. return false;
  92297. };
  92298. /**
  92299. * Fills the nodes to root for bones and builds hierarchy
  92300. */
  92301. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  92302. // Creates nodes for root
  92303. for (var nde in gltfRuntime.nodes) {
  92304. var node = gltfRuntime.nodes[nde];
  92305. var id = nde;
  92306. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  92307. continue;
  92308. }
  92309. // Create node to root bone
  92310. var mat = configureBoneTransformation(node);
  92311. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  92312. bone.id = id;
  92313. nodesToRoot.push({ bone: bone, node: node, id: id });
  92314. }
  92315. // Parenting
  92316. for (var i = 0; i < nodesToRoot.length; i++) {
  92317. var nodeToRoot = nodesToRoot[i];
  92318. var children = nodeToRoot.node.children;
  92319. for (var j = 0; j < children.length; j++) {
  92320. var child = null;
  92321. for (var k = 0; k < nodesToRoot.length; k++) {
  92322. if (nodesToRoot[k].id === children[j]) {
  92323. child = nodesToRoot[k];
  92324. break;
  92325. }
  92326. }
  92327. if (child) {
  92328. child.bone._parent = nodeToRoot.bone;
  92329. nodeToRoot.bone.children.push(child.bone);
  92330. }
  92331. }
  92332. }
  92333. };
  92334. /**
  92335. * Imports a skeleton
  92336. */
  92337. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  92338. if (!newSkeleton) {
  92339. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  92340. }
  92341. if (!skins.babylonSkeleton) {
  92342. return newSkeleton;
  92343. }
  92344. // Find the root bones
  92345. var nodesToRoot = [];
  92346. var nodesToRootToAdd = [];
  92347. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  92348. newSkeleton.bones = [];
  92349. // Joints
  92350. for (var i = 0; i < skins.jointNames.length; i++) {
  92351. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  92352. if (!jointNode) {
  92353. continue;
  92354. }
  92355. var node = jointNode.node;
  92356. if (!node) {
  92357. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  92358. continue;
  92359. }
  92360. var id = jointNode.id;
  92361. // Optimize, if the bone already exists...
  92362. var existingBone = gltfRuntime.scene.getBoneByID(id);
  92363. if (existingBone) {
  92364. newSkeleton.bones.push(existingBone);
  92365. continue;
  92366. }
  92367. // Search for parent bone
  92368. var foundBone = false;
  92369. var parentBone = null;
  92370. for (var j = 0; j < i; j++) {
  92371. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  92372. if (!jointNode_1) {
  92373. continue;
  92374. }
  92375. var joint = jointNode_1.node;
  92376. if (!joint) {
  92377. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  92378. continue;
  92379. }
  92380. var children = joint.children;
  92381. if (!children) {
  92382. continue;
  92383. }
  92384. foundBone = false;
  92385. for (var k = 0; k < children.length; k++) {
  92386. if (children[k] === id) {
  92387. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  92388. foundBone = true;
  92389. break;
  92390. }
  92391. }
  92392. if (foundBone) {
  92393. break;
  92394. }
  92395. }
  92396. // Create bone
  92397. var mat = configureBoneTransformation(node);
  92398. if (!parentBone && nodesToRoot.length > 0) {
  92399. parentBone = getNodeToRoot(nodesToRoot, id);
  92400. if (parentBone) {
  92401. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  92402. nodesToRootToAdd.push(parentBone);
  92403. }
  92404. }
  92405. }
  92406. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  92407. bone.id = id;
  92408. }
  92409. // Polish
  92410. var bones = newSkeleton.bones;
  92411. newSkeleton.bones = [];
  92412. for (var i = 0; i < skins.jointNames.length; i++) {
  92413. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  92414. if (!jointNode) {
  92415. continue;
  92416. }
  92417. for (var j = 0; j < bones.length; j++) {
  92418. if (bones[j].id === jointNode.id) {
  92419. newSkeleton.bones.push(bones[j]);
  92420. break;
  92421. }
  92422. }
  92423. }
  92424. newSkeleton.prepare();
  92425. // Finish
  92426. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  92427. newSkeleton.bones.push(nodesToRootToAdd[i]);
  92428. }
  92429. return newSkeleton;
  92430. };
  92431. /**
  92432. * Imports a mesh and its geometries
  92433. */
  92434. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  92435. if (!newMesh) {
  92436. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  92437. newMesh.id = id;
  92438. }
  92439. if (!node.babylonNode) {
  92440. return newMesh;
  92441. }
  92442. var subMaterials = [];
  92443. var vertexData = null;
  92444. var verticesStarts = new Array();
  92445. var verticesCounts = new Array();
  92446. var indexStarts = new Array();
  92447. var indexCounts = new Array();
  92448. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  92449. var meshID = meshes[meshIndex];
  92450. var mesh = gltfRuntime.meshes[meshID];
  92451. if (!mesh) {
  92452. continue;
  92453. }
  92454. // Positions, normals and UVs
  92455. for (var i = 0; i < mesh.primitives.length; i++) {
  92456. // Temporary vertex data
  92457. var tempVertexData = new BABYLON.VertexData();
  92458. var primitive = mesh.primitives[i];
  92459. if (primitive.mode !== 4) {
  92460. // continue;
  92461. }
  92462. var attributes = primitive.attributes;
  92463. var accessor = null;
  92464. var buffer = null;
  92465. // Set positions, normal and uvs
  92466. for (var semantic in attributes) {
  92467. // Link accessor and buffer view
  92468. accessor = gltfRuntime.accessors[attributes[semantic]];
  92469. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  92470. if (semantic === "NORMAL") {
  92471. tempVertexData.normals = new Float32Array(buffer.length);
  92472. tempVertexData.normals.set(buffer);
  92473. }
  92474. else if (semantic === "POSITION") {
  92475. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  92476. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  92477. for (var j = 0; j < buffer.length; j += 4) {
  92478. tempVertexData.positions[j] = buffer[j];
  92479. tempVertexData.positions[j + 1] = buffer[j + 1];
  92480. tempVertexData.positions[j + 2] = buffer[j + 2];
  92481. }
  92482. }
  92483. else {
  92484. tempVertexData.positions = new Float32Array(buffer.length);
  92485. tempVertexData.positions.set(buffer);
  92486. }
  92487. verticesCounts.push(tempVertexData.positions.length);
  92488. }
  92489. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  92490. var channel = Number(semantic.split("_")[1]);
  92491. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  92492. var uvs = new Float32Array(buffer.length);
  92493. uvs.set(buffer);
  92494. normalizeUVs(uvs);
  92495. tempVertexData.set(uvs, uvKind);
  92496. }
  92497. else if (semantic === "JOINT") {
  92498. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  92499. tempVertexData.matricesIndices.set(buffer);
  92500. }
  92501. else if (semantic === "WEIGHT") {
  92502. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  92503. tempVertexData.matricesWeights.set(buffer);
  92504. }
  92505. else if (semantic === "COLOR") {
  92506. tempVertexData.colors = new Float32Array(buffer.length);
  92507. tempVertexData.colors.set(buffer);
  92508. }
  92509. }
  92510. // Indices
  92511. accessor = gltfRuntime.accessors[primitive.indices];
  92512. if (accessor) {
  92513. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  92514. tempVertexData.indices = new Int32Array(buffer.length);
  92515. tempVertexData.indices.set(buffer);
  92516. indexCounts.push(tempVertexData.indices.length);
  92517. }
  92518. else {
  92519. // Set indices on the fly
  92520. var indices = [];
  92521. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  92522. indices.push(j);
  92523. }
  92524. tempVertexData.indices = new Int32Array(indices);
  92525. indexCounts.push(tempVertexData.indices.length);
  92526. }
  92527. if (!vertexData) {
  92528. vertexData = tempVertexData;
  92529. }
  92530. else {
  92531. vertexData.merge(tempVertexData);
  92532. }
  92533. // Sub material
  92534. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  92535. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  92536. // Update vertices start and index start
  92537. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  92538. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  92539. }
  92540. }
  92541. var material;
  92542. if (subMaterials.length > 1) {
  92543. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  92544. material.subMaterials = subMaterials;
  92545. }
  92546. else {
  92547. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  92548. }
  92549. if (subMaterials.length === 1) {
  92550. material = subMaterials[0];
  92551. }
  92552. if (!newMesh.material) {
  92553. newMesh.material = material;
  92554. }
  92555. // Apply geometry
  92556. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  92557. newMesh.computeWorldMatrix(true);
  92558. // Apply submeshes
  92559. newMesh.subMeshes = [];
  92560. var index = 0;
  92561. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  92562. var meshID = meshes[meshIndex];
  92563. var mesh = gltfRuntime.meshes[meshID];
  92564. if (!mesh) {
  92565. continue;
  92566. }
  92567. for (var i = 0; i < mesh.primitives.length; i++) {
  92568. if (mesh.primitives[i].mode !== 4) {
  92569. //continue;
  92570. }
  92571. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  92572. index++;
  92573. }
  92574. }
  92575. // Finish
  92576. return newMesh;
  92577. };
  92578. /**
  92579. * Configure node transformation from position, rotation and scaling
  92580. */
  92581. var configureNode = function (newNode, position, rotation, scaling) {
  92582. if (newNode.position) {
  92583. newNode.position = position;
  92584. }
  92585. if (newNode.rotationQuaternion || newNode.rotation) {
  92586. newNode.rotationQuaternion = rotation;
  92587. }
  92588. if (newNode.scaling) {
  92589. newNode.scaling = scaling;
  92590. }
  92591. };
  92592. /**
  92593. * Configures node from transformation matrix
  92594. */
  92595. var configureNodeFromMatrix = function (newNode, node, parent) {
  92596. if (node.matrix) {
  92597. var position = new BABYLON.Vector3(0, 0, 0);
  92598. var rotation = new BABYLON.Quaternion();
  92599. var scaling = new BABYLON.Vector3(0, 0, 0);
  92600. var mat = BABYLON.Matrix.FromArray(node.matrix);
  92601. mat.decompose(scaling, rotation, position);
  92602. configureNode(newNode, position, rotation, scaling);
  92603. }
  92604. else if (node.translation && node.rotation && node.scale) {
  92605. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  92606. }
  92607. newNode.computeWorldMatrix(true);
  92608. };
  92609. /**
  92610. * Imports a node
  92611. */
  92612. var importNode = function (gltfRuntime, node, id, parent) {
  92613. var lastNode = null;
  92614. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  92615. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  92616. return null;
  92617. }
  92618. }
  92619. // Meshes
  92620. if (node.skin) {
  92621. if (node.meshes) {
  92622. var skin = gltfRuntime.skins[node.skin];
  92623. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  92624. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  92625. if (newMesh.skeleton === null) {
  92626. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  92627. if (!skin.babylonSkeleton) {
  92628. skin.babylonSkeleton = newMesh.skeleton;
  92629. }
  92630. }
  92631. lastNode = newMesh;
  92632. }
  92633. }
  92634. else if (node.meshes) {
  92635. /**
  92636. * Improve meshes property
  92637. */
  92638. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  92639. lastNode = newMesh;
  92640. }
  92641. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  92642. var light = gltfRuntime.lights[node.light];
  92643. if (light) {
  92644. if (light.type === "ambient") {
  92645. var ambienLight = light[light.type];
  92646. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  92647. hemiLight.name = node.name || "";
  92648. if (ambienLight.color) {
  92649. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  92650. }
  92651. lastNode = hemiLight;
  92652. }
  92653. else if (light.type === "directional") {
  92654. var directionalLight = light[light.type];
  92655. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  92656. dirLight.name = node.name || "";
  92657. if (directionalLight.color) {
  92658. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  92659. }
  92660. lastNode = dirLight;
  92661. }
  92662. else if (light.type === "point") {
  92663. var pointLight = light[light.type];
  92664. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  92665. ptLight.name = node.name || "";
  92666. if (pointLight.color) {
  92667. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  92668. }
  92669. lastNode = ptLight;
  92670. }
  92671. else if (light.type === "spot") {
  92672. var spotLight = light[light.type];
  92673. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  92674. spLight.name = node.name || "";
  92675. if (spotLight.color) {
  92676. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  92677. }
  92678. if (spotLight.fallOfAngle) {
  92679. spLight.angle = spotLight.fallOfAngle;
  92680. }
  92681. if (spotLight.fallOffExponent) {
  92682. spLight.exponent = spotLight.fallOffExponent;
  92683. }
  92684. lastNode = spLight;
  92685. }
  92686. }
  92687. }
  92688. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  92689. var camera = gltfRuntime.cameras[node.camera];
  92690. if (camera) {
  92691. if (camera.type === "orthographic") {
  92692. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  92693. orthoCamera.name = node.name || "";
  92694. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  92695. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  92696. lastNode = orthoCamera;
  92697. }
  92698. else if (camera.type === "perspective") {
  92699. var perspectiveCamera = camera[camera.type];
  92700. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  92701. persCamera.name = node.name || "";
  92702. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  92703. if (!perspectiveCamera.aspectRatio) {
  92704. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  92705. }
  92706. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  92707. persCamera.maxZ = perspectiveCamera.zfar;
  92708. persCamera.minZ = perspectiveCamera.znear;
  92709. }
  92710. lastNode = persCamera;
  92711. }
  92712. }
  92713. }
  92714. // Empty node
  92715. if (!node.jointName) {
  92716. if (node.babylonNode) {
  92717. return node.babylonNode;
  92718. }
  92719. else if (lastNode === null) {
  92720. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  92721. node.babylonNode = dummy;
  92722. lastNode = dummy;
  92723. }
  92724. }
  92725. if (lastNode !== null) {
  92726. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  92727. configureNodeFromMatrix(lastNode, node, parent);
  92728. }
  92729. else {
  92730. var translation = node.translation || [0, 0, 0];
  92731. var rotation = node.rotation || [0, 0, 0, 1];
  92732. var scale = node.scale || [1, 1, 1];
  92733. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  92734. }
  92735. lastNode.updateCache(true);
  92736. node.babylonNode = lastNode;
  92737. }
  92738. return lastNode;
  92739. };
  92740. /**
  92741. * Traverses nodes and creates them
  92742. */
  92743. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  92744. if (meshIncluded === void 0) { meshIncluded = false; }
  92745. var node = gltfRuntime.nodes[id];
  92746. var newNode = null;
  92747. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  92748. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  92749. meshIncluded = true;
  92750. }
  92751. else {
  92752. meshIncluded = false;
  92753. }
  92754. }
  92755. else {
  92756. meshIncluded = true;
  92757. }
  92758. if (!node.jointName && meshIncluded) {
  92759. newNode = importNode(gltfRuntime, node, id, parent);
  92760. if (newNode !== null) {
  92761. newNode.id = id;
  92762. newNode.parent = parent;
  92763. }
  92764. }
  92765. if (node.children) {
  92766. for (var i = 0; i < node.children.length; i++) {
  92767. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  92768. }
  92769. }
  92770. };
  92771. /**
  92772. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  92773. */
  92774. var postLoad = function (gltfRuntime) {
  92775. // Nodes
  92776. var currentScene = gltfRuntime.currentScene;
  92777. if (currentScene) {
  92778. for (var i = 0; i < currentScene.nodes.length; i++) {
  92779. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  92780. }
  92781. }
  92782. else {
  92783. for (var thing in gltfRuntime.scenes) {
  92784. currentScene = gltfRuntime.scenes[thing];
  92785. for (var i = 0; i < currentScene.nodes.length; i++) {
  92786. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  92787. }
  92788. }
  92789. }
  92790. // Set animations
  92791. loadAnimations(gltfRuntime);
  92792. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  92793. var skeleton = gltfRuntime.scene.skeletons[i];
  92794. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  92795. }
  92796. };
  92797. /**
  92798. * onBind shaderrs callback to set uniforms and matrices
  92799. */
  92800. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  92801. var materialValues = material.values || technique.parameters;
  92802. for (var unif in unTreatedUniforms) {
  92803. var uniform = unTreatedUniforms[unif];
  92804. var type = uniform.type;
  92805. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  92806. if (uniform.semantic && !uniform.source && !uniform.node) {
  92807. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  92808. }
  92809. else if (uniform.semantic && (uniform.source || uniform.node)) {
  92810. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  92811. if (source === null) {
  92812. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  92813. }
  92814. if (source === null) {
  92815. continue;
  92816. }
  92817. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  92818. }
  92819. }
  92820. else {
  92821. var value = materialValues[technique.uniforms[unif]];
  92822. if (!value) {
  92823. continue;
  92824. }
  92825. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  92826. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  92827. if (texture === null || texture === undefined) {
  92828. continue;
  92829. }
  92830. shaderMaterial.getEffect().setTexture(unif, texture);
  92831. }
  92832. else {
  92833. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  92834. }
  92835. }
  92836. }
  92837. onSuccess(shaderMaterial);
  92838. };
  92839. /**
  92840. * Prepare uniforms to send the only one time
  92841. * Loads the appropriate textures
  92842. */
  92843. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  92844. var materialValues = material.values || technique.parameters;
  92845. var techniqueUniforms = technique.uniforms;
  92846. /**
  92847. * Prepare values here (not matrices)
  92848. */
  92849. for (var unif in unTreatedUniforms) {
  92850. var uniform = unTreatedUniforms[unif];
  92851. var type = uniform.type;
  92852. var value = materialValues[techniqueUniforms[unif]];
  92853. if (value === undefined) {
  92854. // In case the value is the same for all materials
  92855. value = uniform.value;
  92856. }
  92857. if (!value) {
  92858. continue;
  92859. }
  92860. var onLoadTexture = function (uniformName) {
  92861. return function (texture) {
  92862. if (uniform.value && uniformName) {
  92863. // Static uniform
  92864. shaderMaterial.setTexture(uniformName, texture);
  92865. delete unTreatedUniforms[uniformName];
  92866. }
  92867. };
  92868. };
  92869. // Texture (sampler2D)
  92870. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  92871. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  92872. }
  92873. else {
  92874. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  92875. // Static uniform
  92876. delete unTreatedUniforms[unif];
  92877. }
  92878. }
  92879. }
  92880. };
  92881. /**
  92882. * Shader compilation failed
  92883. */
  92884. var onShaderCompileError = function (program, shaderMaterial, onError) {
  92885. return function (effect, error) {
  92886. shaderMaterial.dispose(true);
  92887. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  92888. };
  92889. };
  92890. /**
  92891. * Shader compilation success
  92892. */
  92893. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  92894. return function (_) {
  92895. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  92896. shaderMaterial.onBind = function (mesh) {
  92897. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  92898. };
  92899. };
  92900. };
  92901. /**
  92902. * Returns the appropriate uniform if already handled by babylon
  92903. */
  92904. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  92905. for (var unif in technique.uniforms) {
  92906. var uniform = technique.uniforms[unif];
  92907. var uniformParameter = technique.parameters[uniform];
  92908. if (tokenizer.currentIdentifier === unif) {
  92909. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  92910. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  92911. if (transformIndex !== -1) {
  92912. delete unTreatedUniforms[unif];
  92913. return babylonTransforms[transformIndex];
  92914. }
  92915. }
  92916. }
  92917. }
  92918. return tokenizer.currentIdentifier;
  92919. };
  92920. /**
  92921. * All shaders loaded. Create materials one by one
  92922. */
  92923. var importMaterials = function (gltfRuntime) {
  92924. // Create materials
  92925. for (var mat in gltfRuntime.materials) {
  92926. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  92927. }
  92928. };
  92929. /**
  92930. * Implementation of the base glTF spec
  92931. */
  92932. var GLTFLoaderBase = /** @class */ (function () {
  92933. function GLTFLoaderBase() {
  92934. }
  92935. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  92936. var gltfRuntime = {
  92937. extensions: {},
  92938. accessors: {},
  92939. buffers: {},
  92940. bufferViews: {},
  92941. meshes: {},
  92942. lights: {},
  92943. cameras: {},
  92944. nodes: {},
  92945. images: {},
  92946. textures: {},
  92947. shaders: {},
  92948. programs: {},
  92949. samplers: {},
  92950. techniques: {},
  92951. materials: {},
  92952. animations: {},
  92953. skins: {},
  92954. extensionsUsed: [],
  92955. scenes: {},
  92956. buffersCount: 0,
  92957. shaderscount: 0,
  92958. scene: scene,
  92959. rootUrl: rootUrl,
  92960. loadedBufferCount: 0,
  92961. loadedBufferViews: {},
  92962. loadedShaderCount: 0,
  92963. importOnlyMeshes: false,
  92964. dummyNodes: []
  92965. };
  92966. // Parse
  92967. if (parsedData.extensions) {
  92968. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  92969. }
  92970. if (parsedData.extensionsUsed) {
  92971. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  92972. }
  92973. if (parsedData.buffers) {
  92974. parseBuffers(parsedData.buffers, gltfRuntime);
  92975. }
  92976. if (parsedData.bufferViews) {
  92977. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  92978. }
  92979. if (parsedData.accessors) {
  92980. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  92981. }
  92982. if (parsedData.meshes) {
  92983. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  92984. }
  92985. if (parsedData.lights) {
  92986. parseObject(parsedData.lights, "lights", gltfRuntime);
  92987. }
  92988. if (parsedData.cameras) {
  92989. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  92990. }
  92991. if (parsedData.nodes) {
  92992. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  92993. }
  92994. if (parsedData.images) {
  92995. parseObject(parsedData.images, "images", gltfRuntime);
  92996. }
  92997. if (parsedData.textures) {
  92998. parseObject(parsedData.textures, "textures", gltfRuntime);
  92999. }
  93000. if (parsedData.shaders) {
  93001. parseShaders(parsedData.shaders, gltfRuntime);
  93002. }
  93003. if (parsedData.programs) {
  93004. parseObject(parsedData.programs, "programs", gltfRuntime);
  93005. }
  93006. if (parsedData.samplers) {
  93007. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  93008. }
  93009. if (parsedData.techniques) {
  93010. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  93011. }
  93012. if (parsedData.materials) {
  93013. parseObject(parsedData.materials, "materials", gltfRuntime);
  93014. }
  93015. if (parsedData.animations) {
  93016. parseObject(parsedData.animations, "animations", gltfRuntime);
  93017. }
  93018. if (parsedData.skins) {
  93019. parseObject(parsedData.skins, "skins", gltfRuntime);
  93020. }
  93021. if (parsedData.scenes) {
  93022. gltfRuntime.scenes = parsedData.scenes;
  93023. }
  93024. if (parsedData.scene && parsedData.scenes) {
  93025. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  93026. }
  93027. return gltfRuntime;
  93028. };
  93029. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  93030. var buffer = gltfRuntime.buffers[id];
  93031. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  93032. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  93033. }
  93034. else {
  93035. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  93036. if (request) {
  93037. onError(request.status + " " + request.statusText);
  93038. }
  93039. });
  93040. }
  93041. };
  93042. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  93043. var texture = gltfRuntime.textures[id];
  93044. if (!texture || !texture.source) {
  93045. onError("");
  93046. return;
  93047. }
  93048. if (texture.babylonTexture) {
  93049. onSuccess(null);
  93050. return;
  93051. }
  93052. var source = gltfRuntime.images[texture.source];
  93053. if (BABYLON.Tools.IsBase64(source.uri)) {
  93054. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  93055. }
  93056. else {
  93057. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  93058. if (request) {
  93059. onError(request.status + " " + request.statusText);
  93060. }
  93061. });
  93062. }
  93063. };
  93064. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  93065. var texture = gltfRuntime.textures[id];
  93066. if (texture.babylonTexture) {
  93067. onSuccess(texture.babylonTexture);
  93068. return;
  93069. }
  93070. var sampler = gltfRuntime.samplers[texture.sampler];
  93071. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  93072. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  93073. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  93074. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  93075. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  93076. var blob = new Blob([buffer]);
  93077. var blobURL = URL.createObjectURL(blob);
  93078. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  93079. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  93080. if (sampler.wrapS !== undefined) {
  93081. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  93082. }
  93083. if (sampler.wrapT !== undefined) {
  93084. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  93085. }
  93086. newTexture.name = id;
  93087. texture.babylonTexture = newTexture;
  93088. onSuccess(newTexture);
  93089. };
  93090. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  93091. var shader = gltfRuntime.shaders[id];
  93092. if (BABYLON.Tools.IsBase64(shader.uri)) {
  93093. var shaderString = atob(shader.uri.split(",")[1]);
  93094. if (onSuccess) {
  93095. onSuccess(shaderString);
  93096. }
  93097. }
  93098. else {
  93099. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  93100. if (request && onError) {
  93101. onError(request.status + " " + request.statusText);
  93102. }
  93103. });
  93104. }
  93105. };
  93106. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  93107. var material = gltfRuntime.materials[id];
  93108. if (!material.technique) {
  93109. if (onError) {
  93110. onError("No technique found.");
  93111. }
  93112. return;
  93113. }
  93114. var technique = gltfRuntime.techniques[material.technique];
  93115. if (!technique) {
  93116. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  93117. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  93118. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  93119. onSuccess(defaultMaterial);
  93120. return;
  93121. }
  93122. var program = gltfRuntime.programs[technique.program];
  93123. var states = technique.states;
  93124. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  93125. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  93126. var newVertexShader = "";
  93127. var newPixelShader = "";
  93128. var vertexTokenizer = new Tokenizer(vertexShader);
  93129. var pixelTokenizer = new Tokenizer(pixelShader);
  93130. var unTreatedUniforms = {};
  93131. var uniforms = [];
  93132. var attributes = [];
  93133. var samplers = [];
  93134. // Fill uniform, sampler2D and attributes
  93135. for (var unif in technique.uniforms) {
  93136. var uniform = technique.uniforms[unif];
  93137. var uniformParameter = technique.parameters[uniform];
  93138. unTreatedUniforms[unif] = uniformParameter;
  93139. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  93140. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  93141. if (transformIndex !== -1) {
  93142. uniforms.push(babylonTransforms[transformIndex]);
  93143. delete unTreatedUniforms[unif];
  93144. }
  93145. else {
  93146. uniforms.push(unif);
  93147. }
  93148. }
  93149. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  93150. samplers.push(unif);
  93151. }
  93152. else {
  93153. uniforms.push(unif);
  93154. }
  93155. }
  93156. for (var attr in technique.attributes) {
  93157. var attribute = technique.attributes[attr];
  93158. var attributeParameter = technique.parameters[attribute];
  93159. if (attributeParameter.semantic) {
  93160. attributes.push(getAttribute(attributeParameter));
  93161. }
  93162. }
  93163. // Configure vertex shader
  93164. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  93165. var tokenType = vertexTokenizer.currentToken;
  93166. if (tokenType !== ETokenType.IDENTIFIER) {
  93167. newVertexShader += vertexTokenizer.currentString;
  93168. continue;
  93169. }
  93170. var foundAttribute = false;
  93171. for (var attr in technique.attributes) {
  93172. var attribute = technique.attributes[attr];
  93173. var attributeParameter = technique.parameters[attribute];
  93174. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  93175. newVertexShader += getAttribute(attributeParameter);
  93176. foundAttribute = true;
  93177. break;
  93178. }
  93179. }
  93180. if (foundAttribute) {
  93181. continue;
  93182. }
  93183. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  93184. }
  93185. // Configure pixel shader
  93186. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  93187. var tokenType = pixelTokenizer.currentToken;
  93188. if (tokenType !== ETokenType.IDENTIFIER) {
  93189. newPixelShader += pixelTokenizer.currentString;
  93190. continue;
  93191. }
  93192. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  93193. }
  93194. // Create shader material
  93195. var shaderPath = {
  93196. vertex: program.vertexShader + id,
  93197. fragment: program.fragmentShader + id
  93198. };
  93199. var options = {
  93200. attributes: attributes,
  93201. uniforms: uniforms,
  93202. samplers: samplers,
  93203. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  93204. };
  93205. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  93206. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  93207. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  93208. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  93209. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  93210. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  93211. if (states && states.functions) {
  93212. var functions = states.functions;
  93213. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  93214. shaderMaterial.backFaceCulling = false;
  93215. }
  93216. var blendFunc = functions.blendFuncSeparate;
  93217. if (blendFunc) {
  93218. 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) {
  93219. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  93220. }
  93221. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  93222. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  93223. }
  93224. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  93225. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  93226. }
  93227. 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) {
  93228. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  93229. }
  93230. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  93231. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  93232. }
  93233. 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) {
  93234. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  93235. }
  93236. }
  93237. }
  93238. };
  93239. return GLTFLoaderBase;
  93240. }());
  93241. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  93242. /**
  93243. * glTF V1 Loader
  93244. */
  93245. var GLTFLoader = /** @class */ (function () {
  93246. function GLTFLoader() {
  93247. // #region Stubs for IGLTFLoader interface
  93248. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  93249. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  93250. this.compileMaterials = false;
  93251. this.useClipPlane = false;
  93252. this.compileShadowGenerators = false;
  93253. this.onDisposeObservable = new BABYLON.Observable();
  93254. this.onMeshLoadedObservable = new BABYLON.Observable();
  93255. this.onTextureLoadedObservable = new BABYLON.Observable();
  93256. this.onMaterialLoadedObservable = new BABYLON.Observable();
  93257. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  93258. this.onCompleteObservable = new BABYLON.Observable();
  93259. this.onExtensionLoadedObservable = new BABYLON.Observable();
  93260. this.state = null;
  93261. }
  93262. GLTFLoader.RegisterExtension = function (extension) {
  93263. if (GLTFLoader.Extensions[extension.name]) {
  93264. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  93265. return;
  93266. }
  93267. GLTFLoader.Extensions[extension.name] = extension;
  93268. };
  93269. GLTFLoader.prototype.dispose = function () { };
  93270. // #endregion
  93271. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  93272. var _this = this;
  93273. scene.useRightHandedSystem = true;
  93274. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  93275. gltfRuntime.importOnlyMeshes = true;
  93276. if (meshesNames === "") {
  93277. gltfRuntime.importMeshesNames = [];
  93278. }
  93279. else if (typeof meshesNames === "string") {
  93280. gltfRuntime.importMeshesNames = [meshesNames];
  93281. }
  93282. else if (meshesNames && !(meshesNames instanceof Array)) {
  93283. gltfRuntime.importMeshesNames = [meshesNames];
  93284. }
  93285. else {
  93286. gltfRuntime.importMeshesNames = [];
  93287. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  93288. }
  93289. // Create nodes
  93290. _this._createNodes(gltfRuntime);
  93291. var meshes = new Array();
  93292. var skeletons = new Array();
  93293. // Fill arrays of meshes and skeletons
  93294. for (var nde in gltfRuntime.nodes) {
  93295. var node = gltfRuntime.nodes[nde];
  93296. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  93297. meshes.push(node.babylonNode);
  93298. }
  93299. }
  93300. for (var skl in gltfRuntime.skins) {
  93301. var skin = gltfRuntime.skins[skl];
  93302. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  93303. skeletons.push(skin.babylonSkeleton);
  93304. }
  93305. }
  93306. // Load buffers, shaders, materials, etc.
  93307. _this._loadBuffersAsync(gltfRuntime, function () {
  93308. _this._loadShadersAsync(gltfRuntime, function () {
  93309. importMaterials(gltfRuntime);
  93310. postLoad(gltfRuntime);
  93311. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  93312. onSuccess(meshes, [], skeletons);
  93313. }
  93314. });
  93315. }, onProgress);
  93316. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  93317. onSuccess(meshes, [], skeletons);
  93318. }
  93319. }, onError);
  93320. return true;
  93321. };
  93322. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  93323. var _this = this;
  93324. return new Promise(function (resolve, reject) {
  93325. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  93326. resolve({
  93327. meshes: meshes,
  93328. particleSystems: particleSystems,
  93329. skeletons: skeletons
  93330. });
  93331. }, onProgress, function (message) {
  93332. reject(new Error(message));
  93333. });
  93334. });
  93335. };
  93336. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  93337. var _this = this;
  93338. scene.useRightHandedSystem = true;
  93339. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  93340. // Load runtime extensios
  93341. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  93342. // Create nodes
  93343. _this._createNodes(gltfRuntime);
  93344. // Load buffers, shaders, materials, etc.
  93345. _this._loadBuffersAsync(gltfRuntime, function () {
  93346. _this._loadShadersAsync(gltfRuntime, function () {
  93347. importMaterials(gltfRuntime);
  93348. postLoad(gltfRuntime);
  93349. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  93350. onSuccess();
  93351. }
  93352. });
  93353. });
  93354. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  93355. onSuccess();
  93356. }
  93357. }, onError);
  93358. }, onError);
  93359. };
  93360. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  93361. var _this = this;
  93362. return new Promise(function (resolve, reject) {
  93363. _this._loadAsync(scene, data, rootUrl, function () {
  93364. resolve();
  93365. }, onProgress, function (message) {
  93366. reject(new Error(message));
  93367. });
  93368. });
  93369. };
  93370. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  93371. var hasShaders = false;
  93372. var processShader = function (sha, shader) {
  93373. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  93374. if (shaderString instanceof ArrayBuffer) {
  93375. return;
  93376. }
  93377. gltfRuntime.loadedShaderCount++;
  93378. if (shaderString) {
  93379. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  93380. }
  93381. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  93382. onload();
  93383. }
  93384. }, function () {
  93385. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  93386. });
  93387. };
  93388. for (var sha in gltfRuntime.shaders) {
  93389. hasShaders = true;
  93390. var shader = gltfRuntime.shaders[sha];
  93391. if (shader) {
  93392. processShader.bind(this, sha, shader)();
  93393. }
  93394. else {
  93395. BABYLON.Tools.Error("No shader named: " + sha);
  93396. }
  93397. }
  93398. if (!hasShaders) {
  93399. onload();
  93400. }
  93401. };
  93402. ;
  93403. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  93404. var hasBuffers = false;
  93405. var processBuffer = function (buf, buffer) {
  93406. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  93407. gltfRuntime.loadedBufferCount++;
  93408. if (bufferView) {
  93409. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  93410. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  93411. }
  93412. gltfRuntime.loadedBufferViews[buf] = bufferView;
  93413. }
  93414. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  93415. onLoad();
  93416. }
  93417. }, function () {
  93418. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  93419. });
  93420. };
  93421. for (var buf in gltfRuntime.buffers) {
  93422. hasBuffers = true;
  93423. var buffer = gltfRuntime.buffers[buf];
  93424. if (buffer) {
  93425. processBuffer.bind(this, buf, buffer)();
  93426. }
  93427. else {
  93428. BABYLON.Tools.Error("No buffer named: " + buf);
  93429. }
  93430. }
  93431. if (!hasBuffers) {
  93432. onLoad();
  93433. }
  93434. };
  93435. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  93436. var currentScene = gltfRuntime.currentScene;
  93437. if (currentScene) {
  93438. // Only one scene even if multiple scenes are defined
  93439. for (var i = 0; i < currentScene.nodes.length; i++) {
  93440. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  93441. }
  93442. }
  93443. else {
  93444. // Load all scenes
  93445. for (var thing in gltfRuntime.scenes) {
  93446. currentScene = gltfRuntime.scenes[thing];
  93447. for (var i = 0; i < currentScene.nodes.length; i++) {
  93448. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  93449. }
  93450. }
  93451. }
  93452. };
  93453. GLTFLoader.Extensions = {};
  93454. return GLTFLoader;
  93455. }());
  93456. GLTF1.GLTFLoader = GLTFLoader;
  93457. ;
  93458. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  93459. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  93460. })(BABYLON || (BABYLON = {}));
  93461. //# sourceMappingURL=babylon.glTFLoader.js.map
  93462. "use strict";
  93463. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  93464. var BABYLON;
  93465. (function (BABYLON) {
  93466. var GLTF1;
  93467. (function (GLTF1) {
  93468. /**
  93469. * Utils functions for GLTF
  93470. */
  93471. var GLTFUtils = /** @class */ (function () {
  93472. function GLTFUtils() {
  93473. }
  93474. /**
  93475. * Sets the given "parameter" matrix
  93476. * @param scene: the {BABYLON.Scene} object
  93477. * @param source: the source node where to pick the matrix
  93478. * @param parameter: the GLTF technique parameter
  93479. * @param uniformName: the name of the shader's uniform
  93480. * @param shaderMaterial: the shader material
  93481. */
  93482. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  93483. var mat = null;
  93484. if (parameter.semantic === "MODEL") {
  93485. mat = source.getWorldMatrix();
  93486. }
  93487. else if (parameter.semantic === "PROJECTION") {
  93488. mat = scene.getProjectionMatrix();
  93489. }
  93490. else if (parameter.semantic === "VIEW") {
  93491. mat = scene.getViewMatrix();
  93492. }
  93493. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  93494. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  93495. }
  93496. else if (parameter.semantic === "MODELVIEW") {
  93497. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  93498. }
  93499. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  93500. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  93501. }
  93502. else if (parameter.semantic === "MODELINVERSE") {
  93503. mat = source.getWorldMatrix().invert();
  93504. }
  93505. else if (parameter.semantic === "VIEWINVERSE") {
  93506. mat = scene.getViewMatrix().invert();
  93507. }
  93508. else if (parameter.semantic === "PROJECTIONINVERSE") {
  93509. mat = scene.getProjectionMatrix().invert();
  93510. }
  93511. else if (parameter.semantic === "MODELVIEWINVERSE") {
  93512. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  93513. }
  93514. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  93515. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  93516. }
  93517. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  93518. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  93519. }
  93520. else {
  93521. debugger;
  93522. }
  93523. if (mat) {
  93524. switch (parameter.type) {
  93525. case GLTF1.EParameterType.FLOAT_MAT2:
  93526. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  93527. break;
  93528. case GLTF1.EParameterType.FLOAT_MAT3:
  93529. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  93530. break;
  93531. case GLTF1.EParameterType.FLOAT_MAT4:
  93532. shaderMaterial.setMatrix(uniformName, mat);
  93533. break;
  93534. default: break;
  93535. }
  93536. }
  93537. };
  93538. /**
  93539. * Sets the given "parameter" matrix
  93540. * @param shaderMaterial: the shader material
  93541. * @param uniform: the name of the shader's uniform
  93542. * @param value: the value of the uniform
  93543. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  93544. */
  93545. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  93546. switch (type) {
  93547. case GLTF1.EParameterType.FLOAT:
  93548. shaderMaterial.setFloat(uniform, value);
  93549. return true;
  93550. case GLTF1.EParameterType.FLOAT_VEC2:
  93551. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  93552. return true;
  93553. case GLTF1.EParameterType.FLOAT_VEC3:
  93554. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  93555. return true;
  93556. case GLTF1.EParameterType.FLOAT_VEC4:
  93557. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  93558. return true;
  93559. default: return false;
  93560. }
  93561. };
  93562. /**
  93563. * Returns the wrap mode of the texture
  93564. * @param mode: the mode value
  93565. */
  93566. GLTFUtils.GetWrapMode = function (mode) {
  93567. switch (mode) {
  93568. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  93569. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  93570. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  93571. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  93572. }
  93573. };
  93574. /**
  93575. * Returns the byte stride giving an accessor
  93576. * @param accessor: the GLTF accessor objet
  93577. */
  93578. GLTFUtils.GetByteStrideFromType = function (accessor) {
  93579. // Needs this function since "byteStride" isn't requiered in glTF format
  93580. var type = accessor.type;
  93581. switch (type) {
  93582. case "VEC2": return 2;
  93583. case "VEC3": return 3;
  93584. case "VEC4": return 4;
  93585. case "MAT2": return 4;
  93586. case "MAT3": return 9;
  93587. case "MAT4": return 16;
  93588. default: return 1;
  93589. }
  93590. };
  93591. /**
  93592. * Returns the texture filter mode giving a mode value
  93593. * @param mode: the filter mode value
  93594. */
  93595. GLTFUtils.GetTextureFilterMode = function (mode) {
  93596. switch (mode) {
  93597. case GLTF1.ETextureFilterType.LINEAR:
  93598. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  93599. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  93600. case GLTF1.ETextureFilterType.NEAREST:
  93601. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  93602. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  93603. }
  93604. };
  93605. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  93606. var byteOffset = bufferView.byteOffset + byteOffset;
  93607. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  93608. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  93609. throw new Error("Buffer access is out of range");
  93610. }
  93611. var buffer = loadedBufferView.buffer;
  93612. byteOffset += loadedBufferView.byteOffset;
  93613. switch (componentType) {
  93614. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  93615. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  93616. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  93617. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  93618. default: return new Float32Array(buffer, byteOffset, byteLength);
  93619. }
  93620. };
  93621. /**
  93622. * Returns a buffer from its accessor
  93623. * @param gltfRuntime: the GLTF runtime
  93624. * @param accessor: the GLTF accessor
  93625. */
  93626. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  93627. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  93628. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  93629. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  93630. };
  93631. /**
  93632. * Decodes a buffer view into a string
  93633. * @param view: the buffer view
  93634. */
  93635. GLTFUtils.DecodeBufferToText = function (view) {
  93636. var result = "";
  93637. var length = view.byteLength;
  93638. for (var i = 0; i < length; ++i) {
  93639. result += String.fromCharCode(view[i]);
  93640. }
  93641. return result;
  93642. };
  93643. /**
  93644. * Returns the default material of gltf. Related to
  93645. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  93646. * @param scene: the Babylon.js scene
  93647. */
  93648. GLTFUtils.GetDefaultMaterial = function (scene) {
  93649. if (!GLTFUtils._DefaultMaterial) {
  93650. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  93651. "precision highp float;",
  93652. "",
  93653. "uniform mat4 worldView;",
  93654. "uniform mat4 projection;",
  93655. "",
  93656. "attribute vec3 position;",
  93657. "",
  93658. "void main(void)",
  93659. "{",
  93660. " gl_Position = projection * worldView * vec4(position, 1.0);",
  93661. "}"
  93662. ].join("\n");
  93663. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  93664. "precision highp float;",
  93665. "",
  93666. "uniform vec4 u_emission;",
  93667. "",
  93668. "void main(void)",
  93669. "{",
  93670. " gl_FragColor = u_emission;",
  93671. "}"
  93672. ].join("\n");
  93673. var shaderPath = {
  93674. vertex: "GLTFDefaultMaterial",
  93675. fragment: "GLTFDefaultMaterial"
  93676. };
  93677. var options = {
  93678. attributes: ["position"],
  93679. uniforms: ["worldView", "projection", "u_emission"],
  93680. samplers: new Array(),
  93681. needAlphaBlending: false
  93682. };
  93683. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  93684. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  93685. }
  93686. return GLTFUtils._DefaultMaterial;
  93687. };
  93688. // The GLTF default material
  93689. GLTFUtils._DefaultMaterial = null;
  93690. return GLTFUtils;
  93691. }());
  93692. GLTF1.GLTFUtils = GLTFUtils;
  93693. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  93694. })(BABYLON || (BABYLON = {}));
  93695. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  93696. "use strict";
  93697. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  93698. var BABYLON;
  93699. (function (BABYLON) {
  93700. var GLTF1;
  93701. (function (GLTF1) {
  93702. var GLTFLoaderExtension = /** @class */ (function () {
  93703. function GLTFLoaderExtension(name) {
  93704. this._name = name;
  93705. }
  93706. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  93707. get: function () {
  93708. return this._name;
  93709. },
  93710. enumerable: true,
  93711. configurable: true
  93712. });
  93713. /**
  93714. * Defines an override for loading the runtime
  93715. * Return true to stop further extensions from loading the runtime
  93716. */
  93717. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  93718. return false;
  93719. };
  93720. /**
  93721. * Defines an onverride for creating gltf runtime
  93722. * Return true to stop further extensions from creating the runtime
  93723. */
  93724. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  93725. return false;
  93726. };
  93727. /**
  93728. * Defines an override for loading buffers
  93729. * Return true to stop further extensions from loading this buffer
  93730. */
  93731. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  93732. return false;
  93733. };
  93734. /**
  93735. * Defines an override for loading texture buffers
  93736. * Return true to stop further extensions from loading this texture data
  93737. */
  93738. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  93739. return false;
  93740. };
  93741. /**
  93742. * Defines an override for creating textures
  93743. * Return true to stop further extensions from loading this texture
  93744. */
  93745. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  93746. return false;
  93747. };
  93748. /**
  93749. * Defines an override for loading shader strings
  93750. * Return true to stop further extensions from loading this shader data
  93751. */
  93752. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  93753. return false;
  93754. };
  93755. /**
  93756. * Defines an override for loading materials
  93757. * Return true to stop further extensions from loading this material
  93758. */
  93759. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  93760. return false;
  93761. };
  93762. // ---------
  93763. // Utilities
  93764. // ---------
  93765. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  93766. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  93767. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  93768. }, function () {
  93769. setTimeout(function () {
  93770. if (!onSuccess) {
  93771. return;
  93772. }
  93773. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  93774. });
  93775. });
  93776. };
  93777. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  93778. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  93779. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  93780. }, function () {
  93781. setTimeout(function () {
  93782. onSuccess();
  93783. });
  93784. });
  93785. };
  93786. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  93787. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  93788. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  93789. }, function () {
  93790. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  93791. });
  93792. };
  93793. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  93794. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  93795. if (buffer) {
  93796. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  93797. }
  93798. }, onError);
  93799. };
  93800. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  93801. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  93802. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  93803. }, function () {
  93804. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  93805. });
  93806. };
  93807. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  93808. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  93809. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  93810. }, function () {
  93811. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  93812. });
  93813. };
  93814. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  93815. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  93816. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  93817. }, function () {
  93818. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  93819. });
  93820. };
  93821. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  93822. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  93823. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  93824. }, function () {
  93825. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  93826. });
  93827. };
  93828. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  93829. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  93830. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  93831. if (func(loaderExtension)) {
  93832. return;
  93833. }
  93834. }
  93835. defaultFunc();
  93836. };
  93837. return GLTFLoaderExtension;
  93838. }());
  93839. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  93840. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  93841. })(BABYLON || (BABYLON = {}));
  93842. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  93843. "use strict";
  93844. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  93845. var BABYLON;
  93846. (function (BABYLON) {
  93847. var GLTF1;
  93848. (function (GLTF1) {
  93849. var BinaryExtensionBufferName = "binary_glTF";
  93850. ;
  93851. ;
  93852. var GLTFBinaryExtension = /** @class */ (function (_super) {
  93853. __extends(GLTFBinaryExtension, _super);
  93854. function GLTFBinaryExtension() {
  93855. return _super.call(this, "KHR_binary_glTF") || this;
  93856. }
  93857. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  93858. var extensionsUsed = data.json.extensionsUsed;
  93859. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  93860. return false;
  93861. }
  93862. this._bin = data.bin;
  93863. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  93864. return true;
  93865. };
  93866. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  93867. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  93868. return false;
  93869. }
  93870. if (id !== BinaryExtensionBufferName) {
  93871. return false;
  93872. }
  93873. onSuccess(this._bin);
  93874. return true;
  93875. };
  93876. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  93877. var texture = gltfRuntime.textures[id];
  93878. var source = gltfRuntime.images[texture.source];
  93879. if (!source.extensions || !(this.name in source.extensions)) {
  93880. return false;
  93881. }
  93882. var sourceExt = source.extensions[this.name];
  93883. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  93884. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  93885. onSuccess(buffer);
  93886. return true;
  93887. };
  93888. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  93889. var shader = gltfRuntime.shaders[id];
  93890. if (!shader.extensions || !(this.name in shader.extensions)) {
  93891. return false;
  93892. }
  93893. var binaryExtensionShader = shader.extensions[this.name];
  93894. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  93895. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  93896. setTimeout(function () {
  93897. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  93898. onSuccess(shaderString);
  93899. });
  93900. return true;
  93901. };
  93902. return GLTFBinaryExtension;
  93903. }(GLTF1.GLTFLoaderExtension));
  93904. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  93905. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  93906. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  93907. })(BABYLON || (BABYLON = {}));
  93908. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  93909. "use strict";
  93910. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  93911. var BABYLON;
  93912. (function (BABYLON) {
  93913. var GLTF1;
  93914. (function (GLTF1) {
  93915. ;
  93916. ;
  93917. ;
  93918. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  93919. __extends(GLTFMaterialsCommonExtension, _super);
  93920. function GLTFMaterialsCommonExtension() {
  93921. return _super.call(this, "KHR_materials_common") || this;
  93922. }
  93923. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  93924. if (!gltfRuntime.extensions)
  93925. return false;
  93926. var extension = gltfRuntime.extensions[this.name];
  93927. if (!extension)
  93928. return false;
  93929. // Create lights
  93930. var lights = extension.lights;
  93931. if (lights) {
  93932. for (var thing in lights) {
  93933. var light = lights[thing];
  93934. switch (light.type) {
  93935. case "ambient":
  93936. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  93937. var ambient = light.ambient;
  93938. if (ambient) {
  93939. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  93940. }
  93941. break;
  93942. case "point":
  93943. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  93944. var point = light.point;
  93945. if (point) {
  93946. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  93947. }
  93948. break;
  93949. case "directional":
  93950. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  93951. var directional = light.directional;
  93952. if (directional) {
  93953. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  93954. }
  93955. break;
  93956. case "spot":
  93957. var spot = light.spot;
  93958. if (spot) {
  93959. 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);
  93960. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  93961. }
  93962. break;
  93963. default:
  93964. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  93965. break;
  93966. }
  93967. }
  93968. }
  93969. return false;
  93970. };
  93971. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  93972. var material = gltfRuntime.materials[id];
  93973. if (!material || !material.extensions)
  93974. return false;
  93975. var extension = material.extensions[this.name];
  93976. if (!extension)
  93977. return false;
  93978. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  93979. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  93980. if (extension.technique === "CONSTANT") {
  93981. standardMaterial.disableLighting = true;
  93982. }
  93983. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  93984. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  93985. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  93986. // Ambient
  93987. if (typeof extension.values.ambient === "string") {
  93988. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  93989. }
  93990. else {
  93991. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  93992. }
  93993. // Diffuse
  93994. if (typeof extension.values.diffuse === "string") {
  93995. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  93996. }
  93997. else {
  93998. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  93999. }
  94000. // Emission
  94001. if (typeof extension.values.emission === "string") {
  94002. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  94003. }
  94004. else {
  94005. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  94006. }
  94007. // Specular
  94008. if (typeof extension.values.specular === "string") {
  94009. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  94010. }
  94011. else {
  94012. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  94013. }
  94014. return true;
  94015. };
  94016. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  94017. // Create buffer from texture url
  94018. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  94019. // Create texture from buffer
  94020. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  94021. }, onError);
  94022. };
  94023. return GLTFMaterialsCommonExtension;
  94024. }(GLTF1.GLTFLoaderExtension));
  94025. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  94026. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  94027. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  94028. })(BABYLON || (BABYLON = {}));
  94029. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  94030. "use strict";
  94031. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  94032. var BABYLON;
  94033. (function (BABYLON) {
  94034. var GLTF2;
  94035. (function (GLTF2) {
  94036. var ArrayItem = /** @class */ (function () {
  94037. function ArrayItem() {
  94038. }
  94039. ArrayItem.Assign = function (values) {
  94040. if (values) {
  94041. for (var index = 0; index < values.length; index++) {
  94042. values[index]._index = index;
  94043. }
  94044. }
  94045. };
  94046. return ArrayItem;
  94047. }());
  94048. GLTF2.ArrayItem = ArrayItem;
  94049. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94050. })(BABYLON || (BABYLON = {}));
  94051. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  94052. "use strict";
  94053. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  94054. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  94055. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  94056. "use strict";
  94057. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  94058. var BABYLON;
  94059. (function (BABYLON) {
  94060. var GLTF2;
  94061. (function (GLTF2) {
  94062. var GLTFLoader = /** @class */ (function () {
  94063. function GLTFLoader() {
  94064. this._completePromises = new Array();
  94065. this._disposed = false;
  94066. this._state = null;
  94067. this._extensions = {};
  94068. this._defaultSampler = {};
  94069. this._defaultBabylonMaterials = {};
  94070. this._requests = new Array();
  94071. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  94072. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  94073. this.compileMaterials = false;
  94074. this.useClipPlane = false;
  94075. this.compileShadowGenerators = false;
  94076. this.onDisposeObservable = new BABYLON.Observable();
  94077. this.onMeshLoadedObservable = new BABYLON.Observable();
  94078. this.onTextureLoadedObservable = new BABYLON.Observable();
  94079. this.onMaterialLoadedObservable = new BABYLON.Observable();
  94080. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  94081. this.onExtensionLoadedObservable = new BABYLON.Observable();
  94082. this.onCompleteObservable = new BABYLON.Observable();
  94083. }
  94084. GLTFLoader._Register = function (name, factory) {
  94085. if (GLTFLoader._Factories[name]) {
  94086. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  94087. return;
  94088. }
  94089. GLTFLoader._Factories[name] = factory;
  94090. // Keep the order of registration so that extensions registered first are called first.
  94091. GLTFLoader._Names.push(name);
  94092. };
  94093. Object.defineProperty(GLTFLoader.prototype, "state", {
  94094. get: function () {
  94095. return this._state;
  94096. },
  94097. enumerable: true,
  94098. configurable: true
  94099. });
  94100. GLTFLoader.prototype.dispose = function () {
  94101. if (this._disposed) {
  94102. return;
  94103. }
  94104. this._disposed = true;
  94105. this.onDisposeObservable.notifyObservers(this);
  94106. this.onDisposeObservable.clear();
  94107. this._clear();
  94108. };
  94109. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  94110. var _this = this;
  94111. return Promise.resolve().then(function () {
  94112. var nodes = null;
  94113. if (meshesNames) {
  94114. var nodeMap_1 = {};
  94115. if (_this._gltf.nodes) {
  94116. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  94117. var node = _a[_i];
  94118. if (node.name) {
  94119. nodeMap_1[node.name] = node;
  94120. }
  94121. }
  94122. }
  94123. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  94124. nodes = names.map(function (name) {
  94125. var node = nodeMap_1[name];
  94126. if (!node) {
  94127. throw new Error("Failed to find node '" + name + "'");
  94128. }
  94129. return node;
  94130. });
  94131. }
  94132. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  94133. return {
  94134. meshes: _this._getMeshes(),
  94135. particleSystems: [],
  94136. skeletons: _this._getSkeletons(),
  94137. };
  94138. });
  94139. });
  94140. };
  94141. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  94142. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  94143. };
  94144. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  94145. var _this = this;
  94146. return Promise.resolve().then(function () {
  94147. _this._loadExtensions();
  94148. _this._babylonScene = scene;
  94149. _this._rootUrl = rootUrl;
  94150. _this._progressCallback = onProgress;
  94151. _this._state = BABYLON.GLTFLoaderState.Loading;
  94152. _this._loadData(data);
  94153. _this._checkExtensions();
  94154. var promises = new Array();
  94155. if (nodes) {
  94156. promises.push(_this._loadNodesAsync(nodes));
  94157. }
  94158. else {
  94159. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  94160. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  94161. }
  94162. if (_this.compileMaterials) {
  94163. promises.push(_this._compileMaterialsAsync());
  94164. }
  94165. if (_this.compileShadowGenerators) {
  94166. promises.push(_this._compileShadowGeneratorsAsync());
  94167. }
  94168. var resultPromise = Promise.all(promises).then(function () {
  94169. _this._state = BABYLON.GLTFLoaderState.Ready;
  94170. _this._startAnimations();
  94171. });
  94172. resultPromise.then(function () {
  94173. _this._rootBabylonMesh.setEnabled(true);
  94174. BABYLON.Tools.SetImmediate(function () {
  94175. if (!_this._disposed) {
  94176. Promise.all(_this._completePromises).then(function () {
  94177. _this._state = BABYLON.GLTFLoaderState.Complete;
  94178. _this.onCompleteObservable.notifyObservers(_this);
  94179. _this.onCompleteObservable.clear();
  94180. _this._clear();
  94181. }).catch(function (error) {
  94182. BABYLON.Tools.Error("glTF Loader: " + error.message);
  94183. _this._clear();
  94184. });
  94185. }
  94186. });
  94187. });
  94188. return resultPromise;
  94189. }).catch(function (error) {
  94190. BABYLON.Tools.Error("glTF Loader: " + error.message);
  94191. _this._clear();
  94192. throw error;
  94193. });
  94194. };
  94195. GLTFLoader.prototype._loadExtensions = function () {
  94196. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  94197. var name_1 = _a[_i];
  94198. var extension = GLTFLoader._Factories[name_1](this);
  94199. this._extensions[name_1] = extension;
  94200. this.onExtensionLoadedObservable.notifyObservers(extension);
  94201. }
  94202. this.onExtensionLoadedObservable.clear();
  94203. };
  94204. GLTFLoader.prototype._loadData = function (data) {
  94205. this._gltf = data.json;
  94206. this._setupData();
  94207. if (data.bin) {
  94208. var buffers = this._gltf.buffers;
  94209. if (buffers && buffers[0] && !buffers[0].uri) {
  94210. var binaryBuffer = buffers[0];
  94211. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  94212. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  94213. }
  94214. binaryBuffer._data = Promise.resolve(data.bin);
  94215. }
  94216. else {
  94217. BABYLON.Tools.Warn("Unexpected BIN chunk");
  94218. }
  94219. }
  94220. };
  94221. GLTFLoader.prototype._setupData = function () {
  94222. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  94223. GLTF2.ArrayItem.Assign(this._gltf.animations);
  94224. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  94225. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  94226. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  94227. GLTF2.ArrayItem.Assign(this._gltf.images);
  94228. GLTF2.ArrayItem.Assign(this._gltf.materials);
  94229. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  94230. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  94231. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  94232. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  94233. GLTF2.ArrayItem.Assign(this._gltf.skins);
  94234. GLTF2.ArrayItem.Assign(this._gltf.textures);
  94235. if (this._gltf.nodes) {
  94236. var nodeParents = {};
  94237. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  94238. var node = _a[_i];
  94239. if (node.children) {
  94240. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  94241. var index = _c[_b];
  94242. nodeParents[index] = node._index;
  94243. }
  94244. }
  94245. }
  94246. var rootNode = this._createRootNode();
  94247. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  94248. var node = _e[_d];
  94249. var parentIndex = nodeParents[node._index];
  94250. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  94251. }
  94252. }
  94253. };
  94254. GLTFLoader.prototype._checkExtensions = function () {
  94255. if (this._gltf.extensionsRequired) {
  94256. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  94257. var name_2 = _a[_i];
  94258. var extension = this._extensions[name_2];
  94259. if (!extension || !extension.enabled) {
  94260. throw new Error("Require extension " + name_2 + " is not available");
  94261. }
  94262. }
  94263. }
  94264. };
  94265. GLTFLoader.prototype._createRootNode = function () {
  94266. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  94267. this._rootBabylonMesh.setEnabled(false);
  94268. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  94269. switch (this.coordinateSystemMode) {
  94270. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  94271. if (!this._babylonScene.useRightHandedSystem) {
  94272. rootNode.rotation = [0, 1, 0, 0];
  94273. rootNode.scale = [1, 1, -1];
  94274. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  94275. }
  94276. break;
  94277. }
  94278. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  94279. this._babylonScene.useRightHandedSystem = true;
  94280. break;
  94281. }
  94282. default: {
  94283. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  94284. }
  94285. }
  94286. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  94287. return rootNode;
  94288. };
  94289. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  94290. var promises = new Array();
  94291. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  94292. var node = nodes_1[_i];
  94293. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  94294. }
  94295. promises.push(this._loadAnimationsAsync());
  94296. return Promise.all(promises).then(function () { });
  94297. };
  94298. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  94299. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  94300. if (promise) {
  94301. return promise;
  94302. }
  94303. var promises = new Array();
  94304. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  94305. var index = _a[_i];
  94306. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  94307. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  94308. }
  94309. promises.push(this._loadAnimationsAsync());
  94310. return Promise.all(promises).then(function () { });
  94311. };
  94312. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  94313. if (node._primitiveBabylonMeshes) {
  94314. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  94315. var babylonMesh = _a[_i];
  94316. callback(babylonMesh);
  94317. }
  94318. }
  94319. else {
  94320. callback(node._babylonMesh);
  94321. }
  94322. };
  94323. GLTFLoader.prototype._getMeshes = function () {
  94324. var meshes = new Array();
  94325. // Root mesh is always first.
  94326. meshes.push(this._rootBabylonMesh);
  94327. var nodes = this._gltf.nodes;
  94328. if (nodes) {
  94329. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  94330. var node = nodes_2[_i];
  94331. if (node._babylonMesh) {
  94332. meshes.push(node._babylonMesh);
  94333. }
  94334. if (node._primitiveBabylonMeshes) {
  94335. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  94336. var babylonMesh = _b[_a];
  94337. meshes.push(babylonMesh);
  94338. }
  94339. }
  94340. }
  94341. }
  94342. return meshes;
  94343. };
  94344. GLTFLoader.prototype._getSkeletons = function () {
  94345. var skeletons = new Array();
  94346. var skins = this._gltf.skins;
  94347. if (skins) {
  94348. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  94349. var skin = skins_1[_i];
  94350. if (skin._babylonSkeleton) {
  94351. skeletons.push(skin._babylonSkeleton);
  94352. }
  94353. }
  94354. }
  94355. return skeletons;
  94356. };
  94357. GLTFLoader.prototype._startAnimations = function () {
  94358. var animations = this._gltf.animations;
  94359. if (!animations) {
  94360. return;
  94361. }
  94362. switch (this.animationStartMode) {
  94363. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  94364. // do nothing
  94365. break;
  94366. }
  94367. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  94368. var animation = animations[0];
  94369. animation._babylonAnimationGroup.start(true);
  94370. break;
  94371. }
  94372. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  94373. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  94374. var animation = animations_1[_i];
  94375. animation._babylonAnimationGroup.start(true);
  94376. }
  94377. break;
  94378. }
  94379. default: {
  94380. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  94381. return;
  94382. }
  94383. }
  94384. };
  94385. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  94386. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  94387. if (promise) {
  94388. return promise;
  94389. }
  94390. if (node._babylonMesh) {
  94391. throw new Error(context + ": Invalid recursive node hierarchy");
  94392. }
  94393. var promises = new Array();
  94394. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  94395. node._babylonMesh = babylonMesh;
  94396. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  94397. node._babylonAnimationTargets.push(babylonMesh);
  94398. GLTFLoader._LoadTransform(node, babylonMesh);
  94399. if (node.mesh != undefined) {
  94400. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  94401. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  94402. }
  94403. if (node.children) {
  94404. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  94405. var index = _a[_i];
  94406. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  94407. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  94408. }
  94409. }
  94410. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  94411. return Promise.all(promises).then(function () { });
  94412. };
  94413. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  94414. // TODO: instancing
  94415. var _this = this;
  94416. var promises = new Array();
  94417. var primitives = mesh.primitives;
  94418. if (!primitives || primitives.length === 0) {
  94419. throw new Error(context + ": Primitives are missing");
  94420. }
  94421. GLTF2.ArrayItem.Assign(primitives);
  94422. if (primitives.length === 1) {
  94423. var primitive = primitives[0];
  94424. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  94425. }
  94426. else {
  94427. node._primitiveBabylonMeshes = [];
  94428. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  94429. var primitive = primitives_1[_i];
  94430. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  94431. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  94432. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  94433. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  94434. }
  94435. }
  94436. if (node.skin != undefined) {
  94437. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  94438. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  94439. }
  94440. return Promise.all(promises).then(function () {
  94441. _this._forEachPrimitive(node, function (babylonMesh) {
  94442. babylonMesh._refreshBoundingInfo(true);
  94443. });
  94444. });
  94445. };
  94446. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  94447. var _this = this;
  94448. var promises = new Array();
  94449. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  94450. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  94451. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  94452. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  94453. }));
  94454. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  94455. if (primitive.material == undefined) {
  94456. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  94457. }
  94458. else {
  94459. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  94460. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  94461. babylonMesh.material = babylonMaterial;
  94462. }));
  94463. }
  94464. return Promise.all(promises).then(function () { });
  94465. };
  94466. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  94467. var _this = this;
  94468. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  94469. if (promise) {
  94470. return promise;
  94471. }
  94472. var attributes = primitive.attributes;
  94473. if (!attributes) {
  94474. throw new Error(context + ": Attributes are missing");
  94475. }
  94476. var promises = new Array();
  94477. var babylonVertexData = new BABYLON.VertexData();
  94478. if (primitive.indices == undefined) {
  94479. var positionAccessorIndex = attributes["POSITION"];
  94480. if (positionAccessorIndex != undefined) {
  94481. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  94482. babylonVertexData.indices = new Uint32Array(accessor.count);
  94483. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  94484. babylonVertexData.indices[i] = i;
  94485. }
  94486. }
  94487. }
  94488. else {
  94489. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  94490. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  94491. babylonVertexData.indices = data;
  94492. }));
  94493. }
  94494. var loadAttribute = function (attribute, kind) {
  94495. if (attributes[attribute] == undefined) {
  94496. return;
  94497. }
  94498. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  94499. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  94500. babylonMesh._delayInfo.push(kind);
  94501. }
  94502. if (attribute === "COLOR_0") {
  94503. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  94504. babylonMesh.hasVertexAlpha = true;
  94505. }
  94506. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  94507. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  94508. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  94509. if (attribute === "COLOR_0" && accessor.type === "VEC3") {
  94510. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  94511. }
  94512. babylonVertexData.set(attributeData, kind);
  94513. }));
  94514. };
  94515. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  94516. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  94517. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  94518. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  94519. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  94520. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  94521. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  94522. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  94523. return Promise.all(promises).then(function () {
  94524. return babylonVertexData;
  94525. });
  94526. };
  94527. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  94528. if (!primitive.targets) {
  94529. return;
  94530. }
  94531. if (node._numMorphTargets == undefined) {
  94532. node._numMorphTargets = primitive.targets.length;
  94533. }
  94534. else if (primitive.targets.length !== node._numMorphTargets) {
  94535. throw new Error(context + ": Primitives do not have the same number of targets");
  94536. }
  94537. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  94538. for (var index = 0; index < primitive.targets.length; index++) {
  94539. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  94540. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  94541. // TODO: tell the target whether it has positions, normals, tangents
  94542. }
  94543. };
  94544. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  94545. if (!primitive.targets) {
  94546. return Promise.resolve();
  94547. }
  94548. var promises = new Array();
  94549. var morphTargetManager = babylonMesh.morphTargetManager;
  94550. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  94551. var babylonMorphTarget = morphTargetManager.getTarget(index);
  94552. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  94553. }
  94554. return Promise.all(promises).then(function () { });
  94555. };
  94556. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  94557. var _this = this;
  94558. var promises = new Array();
  94559. var loadAttribute = function (attribute, setData) {
  94560. if (attributes[attribute] == undefined) {
  94561. return;
  94562. }
  94563. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  94564. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  94565. setData(data);
  94566. }));
  94567. };
  94568. loadAttribute("POSITION", function (data) {
  94569. if (babylonVertexData.positions) {
  94570. for (var i = 0; i < data.length; i++) {
  94571. data[i] += babylonVertexData.positions[i];
  94572. }
  94573. babylonMorphTarget.setPositions(data);
  94574. }
  94575. });
  94576. loadAttribute("NORMAL", function (data) {
  94577. if (babylonVertexData.normals) {
  94578. for (var i = 0; i < data.length; i++) {
  94579. data[i] += babylonVertexData.normals[i];
  94580. }
  94581. babylonMorphTarget.setNormals(data);
  94582. }
  94583. });
  94584. loadAttribute("TANGENT", function (data) {
  94585. if (babylonVertexData.tangents) {
  94586. // Tangent data for morph targets is stored as xyz delta.
  94587. // The vertexData.tangent is stored as xyzw.
  94588. // So we need to skip every fourth vertexData.tangent.
  94589. for (var i = 0, j = 0; i < data.length; i++) {
  94590. data[i] += babylonVertexData.tangents[j++];
  94591. if ((i + 1) % 3 == 0) {
  94592. j++;
  94593. }
  94594. }
  94595. babylonMorphTarget.setTangents(data);
  94596. }
  94597. });
  94598. return Promise.all(promises).then(function () { });
  94599. };
  94600. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  94601. if (accessor.componentType == 5126 /* FLOAT */) {
  94602. return data;
  94603. }
  94604. var factor = 1;
  94605. if (accessor.normalized) {
  94606. switch (accessor.componentType) {
  94607. case 5121 /* UNSIGNED_BYTE */: {
  94608. factor = 1 / 255;
  94609. break;
  94610. }
  94611. case 5123 /* UNSIGNED_SHORT */: {
  94612. factor = 1 / 65535;
  94613. break;
  94614. }
  94615. default: {
  94616. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  94617. }
  94618. }
  94619. }
  94620. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  94621. for (var i = 0; i < result.length; i++) {
  94622. result[i] = data[i] * factor;
  94623. }
  94624. return result;
  94625. };
  94626. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  94627. var result = new Float32Array(data.length / 3 * 4);
  94628. var offset = 0;
  94629. for (var i = 0; i < result.length; i++) {
  94630. if ((i + 1) % 4 === 0) {
  94631. result[i] = 1;
  94632. }
  94633. else {
  94634. result[i] = data[offset++];
  94635. }
  94636. }
  94637. return result;
  94638. };
  94639. GLTFLoader._LoadTransform = function (node, babylonNode) {
  94640. var position = BABYLON.Vector3.Zero();
  94641. var rotation = BABYLON.Quaternion.Identity();
  94642. var scaling = BABYLON.Vector3.One();
  94643. if (node.matrix) {
  94644. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  94645. matrix.decompose(scaling, rotation, position);
  94646. }
  94647. else {
  94648. if (node.translation)
  94649. position = BABYLON.Vector3.FromArray(node.translation);
  94650. if (node.rotation)
  94651. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  94652. if (node.scale)
  94653. scaling = BABYLON.Vector3.FromArray(node.scale);
  94654. }
  94655. babylonNode.position = position;
  94656. babylonNode.rotationQuaternion = rotation;
  94657. babylonNode.scaling = scaling;
  94658. };
  94659. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  94660. var _this = this;
  94661. var assignSkeleton = function () {
  94662. _this._forEachPrimitive(node, function (babylonMesh) {
  94663. babylonMesh.skeleton = skin._babylonSkeleton;
  94664. });
  94665. node._babylonMesh.parent = _this._rootBabylonMesh;
  94666. node._babylonMesh.position = BABYLON.Vector3.Zero();
  94667. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  94668. node._babylonMesh.scaling = BABYLON.Vector3.One();
  94669. };
  94670. if (skin._loaded) {
  94671. return skin._loaded.then(function () {
  94672. assignSkeleton();
  94673. });
  94674. }
  94675. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  94676. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  94677. var skeletonId = "skeleton" + skin._index;
  94678. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  94679. skin._babylonSkeleton = babylonSkeleton;
  94680. _this._loadBones(context, skin, inverseBindMatricesData);
  94681. assignSkeleton();
  94682. }));
  94683. };
  94684. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  94685. if (skin.inverseBindMatrices == undefined) {
  94686. return Promise.resolve(null);
  94687. }
  94688. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  94689. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  94690. return data;
  94691. });
  94692. };
  94693. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  94694. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  94695. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  94696. node._babylonAnimationTargets.push(babylonBone);
  94697. return babylonBone;
  94698. };
  94699. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  94700. var babylonBones = {};
  94701. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  94702. var index = _a[_i];
  94703. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  94704. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  94705. }
  94706. };
  94707. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  94708. var babylonBone = babylonBones[node._index];
  94709. if (babylonBone) {
  94710. return babylonBone;
  94711. }
  94712. var boneIndex = skin.joints.indexOf(node._index);
  94713. var baseMatrix = BABYLON.Matrix.Identity();
  94714. if (inverseBindMatricesData && boneIndex !== -1) {
  94715. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  94716. baseMatrix.invertToRef(baseMatrix);
  94717. }
  94718. var babylonParentBone = null;
  94719. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  94720. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  94721. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  94722. }
  94723. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  94724. babylonBones[node._index] = babylonBone;
  94725. return babylonBone;
  94726. };
  94727. GLTFLoader.prototype._getNodeMatrix = function (node) {
  94728. return node.matrix ?
  94729. BABYLON.Matrix.FromArray(node.matrix) :
  94730. 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());
  94731. };
  94732. GLTFLoader.prototype._loadAnimationsAsync = function () {
  94733. var animations = this._gltf.animations;
  94734. if (!animations) {
  94735. return Promise.resolve();
  94736. }
  94737. var promises = new Array();
  94738. for (var index = 0; index < animations.length; index++) {
  94739. var animation = animations[index];
  94740. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  94741. }
  94742. return Promise.all(promises).then(function () { });
  94743. };
  94744. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  94745. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  94746. animation._babylonAnimationGroup = babylonAnimationGroup;
  94747. var promises = new Array();
  94748. GLTF2.ArrayItem.Assign(animation.channels);
  94749. GLTF2.ArrayItem.Assign(animation.samplers);
  94750. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  94751. var channel = _a[_i];
  94752. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  94753. }
  94754. this.onAnimationGroupLoadedObservable.notifyObservers(babylonAnimationGroup);
  94755. return Promise.all(promises).then(function () {
  94756. babylonAnimationGroup.normalize();
  94757. });
  94758. };
  94759. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  94760. var _this = this;
  94761. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  94762. if (!targetNode._babylonMesh || targetNode.skin != undefined) {
  94763. return Promise.resolve();
  94764. }
  94765. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  94766. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  94767. var targetPath;
  94768. var animationType;
  94769. switch (channel.target.path) {
  94770. case "translation" /* TRANSLATION */: {
  94771. targetPath = "position";
  94772. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  94773. break;
  94774. }
  94775. case "rotation" /* ROTATION */: {
  94776. targetPath = "rotationQuaternion";
  94777. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  94778. break;
  94779. }
  94780. case "scale" /* SCALE */: {
  94781. targetPath = "scaling";
  94782. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  94783. break;
  94784. }
  94785. case "weights" /* WEIGHTS */: {
  94786. targetPath = "influence";
  94787. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  94788. break;
  94789. }
  94790. default: {
  94791. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  94792. }
  94793. }
  94794. var outputBufferOffset = 0;
  94795. var getNextOutputValue;
  94796. switch (targetPath) {
  94797. case "position": {
  94798. getNextOutputValue = function () {
  94799. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  94800. outputBufferOffset += 3;
  94801. return value;
  94802. };
  94803. break;
  94804. }
  94805. case "rotationQuaternion": {
  94806. getNextOutputValue = function () {
  94807. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  94808. outputBufferOffset += 4;
  94809. return value;
  94810. };
  94811. break;
  94812. }
  94813. case "scaling": {
  94814. getNextOutputValue = function () {
  94815. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  94816. outputBufferOffset += 3;
  94817. return value;
  94818. };
  94819. break;
  94820. }
  94821. case "influence": {
  94822. getNextOutputValue = function () {
  94823. var value = new Array(targetNode._numMorphTargets);
  94824. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  94825. value[i] = data.output[outputBufferOffset++];
  94826. }
  94827. return value;
  94828. };
  94829. break;
  94830. }
  94831. }
  94832. var getNextKey;
  94833. switch (data.interpolation) {
  94834. case "STEP" /* STEP */: {
  94835. getNextKey = function (frameIndex) { return ({
  94836. frame: data.input[frameIndex],
  94837. value: getNextOutputValue(),
  94838. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  94839. }); };
  94840. break;
  94841. }
  94842. case "LINEAR" /* LINEAR */: {
  94843. getNextKey = function (frameIndex) { return ({
  94844. frame: data.input[frameIndex],
  94845. value: getNextOutputValue()
  94846. }); };
  94847. break;
  94848. }
  94849. case "CUBICSPLINE" /* CUBICSPLINE */: {
  94850. getNextKey = function (frameIndex) { return ({
  94851. frame: data.input[frameIndex],
  94852. inTangent: getNextOutputValue(),
  94853. value: getNextOutputValue(),
  94854. outTangent: getNextOutputValue()
  94855. }); };
  94856. break;
  94857. }
  94858. }
  94859. var keys = new Array(data.input.length);
  94860. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  94861. keys[frameIndex] = getNextKey(frameIndex);
  94862. }
  94863. if (targetPath === "influence") {
  94864. var _loop_1 = function (targetIndex) {
  94865. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  94866. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  94867. babylonAnimation.setKeys(keys.map(function (key) { return ({
  94868. frame: key.frame,
  94869. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  94870. value: key.value[targetIndex],
  94871. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  94872. }); }));
  94873. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  94874. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  94875. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  94876. });
  94877. };
  94878. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  94879. _loop_1(targetIndex);
  94880. }
  94881. }
  94882. else {
  94883. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  94884. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  94885. babylonAnimation.setKeys(keys);
  94886. if (targetNode._babylonAnimationTargets) {
  94887. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  94888. var target = _a[_i];
  94889. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  94890. }
  94891. }
  94892. }
  94893. });
  94894. };
  94895. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  94896. if (sampler._data) {
  94897. return sampler._data;
  94898. }
  94899. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  94900. switch (interpolation) {
  94901. case "STEP" /* STEP */:
  94902. case "LINEAR" /* LINEAR */:
  94903. case "CUBICSPLINE" /* CUBICSPLINE */: {
  94904. break;
  94905. }
  94906. default: {
  94907. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  94908. }
  94909. }
  94910. var inputData;
  94911. var outputData;
  94912. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  94913. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  94914. sampler._data = Promise.all([
  94915. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  94916. inputData = data;
  94917. }),
  94918. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  94919. outputData = data;
  94920. })
  94921. ]).then(function () {
  94922. return {
  94923. input: inputData,
  94924. interpolation: interpolation,
  94925. output: outputData,
  94926. };
  94927. });
  94928. return sampler._data;
  94929. };
  94930. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  94931. if (buffer._data) {
  94932. return buffer._data;
  94933. }
  94934. if (!buffer.uri) {
  94935. throw new Error(context + ": Uri is missing");
  94936. }
  94937. buffer._data = this._loadUriAsync(context, buffer.uri);
  94938. return buffer._data;
  94939. };
  94940. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  94941. if (bufferView._data) {
  94942. return bufferView._data;
  94943. }
  94944. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  94945. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  94946. try {
  94947. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  94948. }
  94949. catch (e) {
  94950. throw new Error(context + ": " + e.message);
  94951. }
  94952. });
  94953. return bufferView._data;
  94954. };
  94955. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  94956. var _this = this;
  94957. if (accessor.sparse) {
  94958. throw new Error(context + ": Sparse accessors are not currently supported");
  94959. }
  94960. if (accessor._data) {
  94961. return accessor._data;
  94962. }
  94963. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  94964. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  94965. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  94966. var byteOffset = accessor.byteOffset || 0;
  94967. var byteStride = bufferView.byteStride;
  94968. if (byteStride === 0) {
  94969. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  94970. }
  94971. try {
  94972. switch (accessor.componentType) {
  94973. case 5120 /* BYTE */: {
  94974. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  94975. }
  94976. case 5121 /* UNSIGNED_BYTE */: {
  94977. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  94978. }
  94979. case 5122 /* SHORT */: {
  94980. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  94981. }
  94982. case 5123 /* UNSIGNED_SHORT */: {
  94983. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  94984. }
  94985. case 5125 /* UNSIGNED_INT */: {
  94986. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  94987. }
  94988. case 5126 /* FLOAT */: {
  94989. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  94990. }
  94991. default: {
  94992. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  94993. }
  94994. }
  94995. }
  94996. catch (e) {
  94997. throw new Error(context + ": " + e.messsage);
  94998. }
  94999. });
  95000. return accessor._data;
  95001. };
  95002. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  95003. byteOffset += data.byteOffset;
  95004. var targetLength = count * numComponents;
  95005. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  95006. return new typedArray(data.buffer, byteOffset, targetLength);
  95007. }
  95008. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  95009. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  95010. var targetBuffer = new typedArray(targetLength);
  95011. var sourceIndex = 0;
  95012. var targetIndex = 0;
  95013. while (targetIndex < targetLength) {
  95014. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  95015. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  95016. targetIndex++;
  95017. }
  95018. sourceIndex += elementStride;
  95019. }
  95020. return targetBuffer;
  95021. };
  95022. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  95023. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  95024. if (!babylonMaterial) {
  95025. babylonMaterial = this._createMaterial(BABYLON.PBRMaterial, "__gltf_default", drawMode);
  95026. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  95027. babylonMaterial.metallic = 1;
  95028. babylonMaterial.roughness = 1;
  95029. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  95030. }
  95031. return babylonMaterial;
  95032. };
  95033. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  95034. var promises = new Array();
  95035. // Ensure metallic workflow
  95036. babylonMaterial.metallic = 1;
  95037. babylonMaterial.roughness = 1;
  95038. var properties = material.pbrMetallicRoughness;
  95039. if (properties) {
  95040. if (properties.baseColorFactor) {
  95041. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  95042. babylonMaterial.alpha = properties.baseColorFactor[3];
  95043. }
  95044. else {
  95045. babylonMaterial.albedoColor = BABYLON.Color3.White();
  95046. }
  95047. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  95048. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  95049. if (properties.baseColorTexture) {
  95050. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  95051. babylonMaterial.albedoTexture = texture;
  95052. }));
  95053. }
  95054. if (properties.metallicRoughnessTexture) {
  95055. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  95056. babylonMaterial.metallicTexture = texture;
  95057. }));
  95058. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  95059. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  95060. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  95061. }
  95062. }
  95063. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  95064. return Promise.all(promises).then(function () { });
  95065. };
  95066. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  95067. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, babylonDrawMode, assign);
  95068. if (promise) {
  95069. return promise;
  95070. }
  95071. material._babylonData = material._babylonData || {};
  95072. var babylonData = material._babylonData[babylonDrawMode];
  95073. if (!babylonData) {
  95074. var promises = new Array();
  95075. var name_3 = material.name || "materialSG_" + material._index;
  95076. var babylonMaterial = this._createMaterial(BABYLON.PBRMaterial, name_3, babylonDrawMode);
  95077. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  95078. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  95079. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  95080. babylonData = {
  95081. material: babylonMaterial,
  95082. meshes: [],
  95083. loaded: Promise.all(promises).then(function () { })
  95084. };
  95085. material._babylonData[babylonDrawMode] = babylonData;
  95086. }
  95087. babylonData.meshes.push(babylonMesh);
  95088. assign(babylonData.material);
  95089. return babylonData.loaded;
  95090. };
  95091. GLTFLoader.prototype._createMaterial = function (type, name, drawMode) {
  95092. var babylonMaterial = new type(name, this._babylonScene);
  95093. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  95094. babylonMaterial.fillMode = drawMode;
  95095. return babylonMaterial;
  95096. };
  95097. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  95098. var promises = new Array();
  95099. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  95100. if (material.doubleSided) {
  95101. babylonMaterial.backFaceCulling = false;
  95102. babylonMaterial.twoSidedLighting = true;
  95103. }
  95104. if (material.normalTexture) {
  95105. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  95106. babylonMaterial.bumpTexture = texture;
  95107. }));
  95108. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  95109. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  95110. if (material.normalTexture.scale != undefined) {
  95111. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  95112. }
  95113. }
  95114. if (material.occlusionTexture) {
  95115. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  95116. babylonMaterial.ambientTexture = texture;
  95117. }));
  95118. babylonMaterial.useAmbientInGrayScale = true;
  95119. if (material.occlusionTexture.strength != undefined) {
  95120. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  95121. }
  95122. }
  95123. if (material.emissiveTexture) {
  95124. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  95125. babylonMaterial.emissiveTexture = texture;
  95126. }));
  95127. }
  95128. return Promise.all(promises).then(function () { });
  95129. };
  95130. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  95131. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  95132. switch (alphaMode) {
  95133. case "OPAQUE" /* OPAQUE */: {
  95134. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  95135. break;
  95136. }
  95137. case "MASK" /* MASK */: {
  95138. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  95139. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  95140. if (babylonMaterial.albedoTexture) {
  95141. babylonMaterial.albedoTexture.hasAlpha = true;
  95142. }
  95143. break;
  95144. }
  95145. case "BLEND" /* BLEND */: {
  95146. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  95147. if (babylonMaterial.albedoTexture) {
  95148. babylonMaterial.albedoTexture.hasAlpha = true;
  95149. babylonMaterial.useAlphaFromAlbedoTexture = true;
  95150. }
  95151. break;
  95152. }
  95153. default: {
  95154. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  95155. }
  95156. }
  95157. };
  95158. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  95159. var _this = this;
  95160. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  95161. context = "#/textures/" + textureInfo.index;
  95162. var promises = new Array();
  95163. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  95164. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  95165. var deferred = new BABYLON.Deferred();
  95166. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  95167. if (!_this._disposed) {
  95168. deferred.resolve();
  95169. }
  95170. }, function (message, exception) {
  95171. if (!_this._disposed) {
  95172. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  95173. }
  95174. });
  95175. promises.push(deferred.promise);
  95176. babylonTexture.name = texture.name || "texture" + texture._index;
  95177. babylonTexture.wrapU = samplerData.wrapU;
  95178. babylonTexture.wrapV = samplerData.wrapV;
  95179. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  95180. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  95181. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  95182. babylonTexture.updateURL(objectURL);
  95183. }));
  95184. assign(babylonTexture);
  95185. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  95186. return Promise.all(promises).then(function () { });
  95187. };
  95188. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  95189. if (!sampler._data) {
  95190. sampler._data = {
  95191. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  95192. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  95193. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  95194. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  95195. };
  95196. }
  95197. ;
  95198. return sampler._data;
  95199. };
  95200. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  95201. if (image._objectURL) {
  95202. return image._objectURL;
  95203. }
  95204. var promise;
  95205. if (image.uri) {
  95206. promise = this._loadUriAsync(context, image.uri);
  95207. }
  95208. else {
  95209. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  95210. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  95211. }
  95212. image._objectURL = promise.then(function (data) {
  95213. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  95214. });
  95215. return image._objectURL;
  95216. };
  95217. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  95218. var _this = this;
  95219. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  95220. if (promise) {
  95221. return promise;
  95222. }
  95223. if (!GLTFLoader._ValidateUri(uri)) {
  95224. throw new Error(context + ": Uri '" + uri + "' is invalid");
  95225. }
  95226. if (BABYLON.Tools.IsBase64(uri)) {
  95227. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  95228. }
  95229. return new Promise(function (resolve, reject) {
  95230. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  95231. if (!_this._disposed) {
  95232. resolve(new Uint8Array(data));
  95233. }
  95234. }, function (event) {
  95235. if (!_this._disposed) {
  95236. try {
  95237. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  95238. request._lengthComputable = event.lengthComputable;
  95239. request._loaded = event.loaded;
  95240. request._total = event.total;
  95241. _this._onProgress();
  95242. }
  95243. }
  95244. catch (e) {
  95245. reject(e);
  95246. }
  95247. }
  95248. }, _this._babylonScene.database, true, function (request, exception) {
  95249. if (!_this._disposed) {
  95250. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  95251. }
  95252. });
  95253. _this._requests.push(request);
  95254. });
  95255. };
  95256. GLTFLoader.prototype._onProgress = function () {
  95257. if (!this._progressCallback) {
  95258. return;
  95259. }
  95260. var lengthComputable = true;
  95261. var loaded = 0;
  95262. var total = 0;
  95263. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  95264. var request = _a[_i];
  95265. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  95266. return;
  95267. }
  95268. lengthComputable = lengthComputable && request._lengthComputable;
  95269. loaded += request._loaded;
  95270. total += request._total;
  95271. }
  95272. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  95273. };
  95274. GLTFLoader._GetProperty = function (context, array, index) {
  95275. if (!array || index == undefined || !array[index]) {
  95276. throw new Error(context + ": Failed to find index (" + index + ")");
  95277. }
  95278. return array[index];
  95279. };
  95280. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  95281. // Set defaults if undefined
  95282. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  95283. switch (mode) {
  95284. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  95285. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  95286. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  95287. default:
  95288. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  95289. return BABYLON.Texture.WRAP_ADDRESSMODE;
  95290. }
  95291. };
  95292. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  95293. // Set defaults if undefined
  95294. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  95295. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  95296. if (magFilter === 9729 /* LINEAR */) {
  95297. switch (minFilter) {
  95298. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  95299. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  95300. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  95301. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  95302. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  95303. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  95304. default:
  95305. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  95306. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  95307. }
  95308. }
  95309. else {
  95310. if (magFilter !== 9728 /* NEAREST */) {
  95311. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  95312. }
  95313. switch (minFilter) {
  95314. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  95315. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  95316. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  95317. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  95318. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  95319. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  95320. default:
  95321. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  95322. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  95323. }
  95324. }
  95325. };
  95326. GLTFLoader._GetNumComponents = function (context, type) {
  95327. switch (type) {
  95328. case "SCALAR": return 1;
  95329. case "VEC2": return 2;
  95330. case "VEC3": return 3;
  95331. case "VEC4": return 4;
  95332. case "MAT2": return 4;
  95333. case "MAT3": return 9;
  95334. case "MAT4": return 16;
  95335. }
  95336. throw new Error(context + ": Invalid type (" + type + ")");
  95337. };
  95338. GLTFLoader._ValidateUri = function (uri) {
  95339. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  95340. };
  95341. GLTFLoader._GetDrawMode = function (context, mode) {
  95342. if (mode == undefined) {
  95343. mode = 4 /* TRIANGLES */;
  95344. }
  95345. switch (mode) {
  95346. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  95347. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  95348. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  95349. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  95350. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  95351. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  95352. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  95353. }
  95354. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  95355. };
  95356. GLTFLoader.prototype._compileMaterialsAsync = function () {
  95357. var promises = new Array();
  95358. if (this._gltf.materials) {
  95359. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  95360. var material = _a[_i];
  95361. if (material._babylonData) {
  95362. for (var babylonDrawMode in material._babylonData) {
  95363. var babylonData = material._babylonData[babylonDrawMode];
  95364. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  95365. var babylonMesh = _c[_b];
  95366. // Ensure nonUniformScaling is set if necessary.
  95367. babylonMesh.computeWorldMatrix(true);
  95368. var babylonMaterial = babylonData.material;
  95369. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  95370. if (this.useClipPlane) {
  95371. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  95372. }
  95373. }
  95374. }
  95375. }
  95376. }
  95377. }
  95378. return Promise.all(promises).then(function () { });
  95379. };
  95380. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  95381. var promises = new Array();
  95382. var lights = this._babylonScene.lights;
  95383. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  95384. var light = lights_1[_i];
  95385. var generator = light.getShadowGenerator();
  95386. if (generator) {
  95387. promises.push(generator.forceCompilationAsync());
  95388. }
  95389. }
  95390. return Promise.all(promises).then(function () { });
  95391. };
  95392. GLTFLoader.prototype._clear = function () {
  95393. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  95394. var request = _a[_i];
  95395. request.abort();
  95396. }
  95397. this._requests.length = 0;
  95398. if (this._gltf && this._gltf.images) {
  95399. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  95400. var image = _c[_b];
  95401. if (image._objectURL) {
  95402. image._objectURL.then(function (value) {
  95403. URL.revokeObjectURL(value);
  95404. });
  95405. image._objectURL = undefined;
  95406. }
  95407. }
  95408. }
  95409. delete this._gltf;
  95410. delete this._babylonScene;
  95411. this._completePromises.length = 0;
  95412. for (var name_4 in this._extensions) {
  95413. this._extensions[name_4].dispose();
  95414. }
  95415. this._extensions = {};
  95416. delete this._rootBabylonMesh;
  95417. delete this._progressCallback;
  95418. this.onMeshLoadedObservable.clear();
  95419. this.onTextureLoadedObservable.clear();
  95420. this.onMaterialLoadedObservable.clear();
  95421. };
  95422. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  95423. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  95424. var name_5 = _a[_i];
  95425. var extension = this._extensions[name_5];
  95426. if (extension.enabled) {
  95427. var promise = actionAsync(extension);
  95428. if (promise) {
  95429. return promise;
  95430. }
  95431. }
  95432. }
  95433. return null;
  95434. };
  95435. GLTFLoader._Names = new Array();
  95436. GLTFLoader._Factories = {};
  95437. return GLTFLoader;
  95438. }());
  95439. GLTF2.GLTFLoader = GLTFLoader;
  95440. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  95441. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  95442. })(BABYLON || (BABYLON = {}));
  95443. //# sourceMappingURL=babylon.glTFLoader.js.map
  95444. "use strict";
  95445. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  95446. var BABYLON;
  95447. (function (BABYLON) {
  95448. var GLTF2;
  95449. (function (GLTF2) {
  95450. var GLTFLoaderExtension = /** @class */ (function () {
  95451. function GLTFLoaderExtension(loader) {
  95452. this.enabled = true;
  95453. this._loader = loader;
  95454. }
  95455. GLTFLoaderExtension.prototype.dispose = function () {
  95456. delete this._loader;
  95457. };
  95458. // #region Overridable Methods
  95459. /** Override this method to modify the default behavior for loading scenes. */
  95460. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  95461. /** Override this method to modify the default behavior for loading nodes. */
  95462. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  95463. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  95464. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  95465. /** Override this method to modify the default behavior for loading materials. */
  95466. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) { return null; };
  95467. /** Override this method to modify the default behavior for loading uris. */
  95468. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  95469. // #endregion
  95470. /** Helper method called by a loader extension to load an glTF extension. */
  95471. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  95472. if (!property.extensions) {
  95473. return null;
  95474. }
  95475. var extensions = property.extensions;
  95476. var extension = extensions[this.name];
  95477. if (!extension) {
  95478. return null;
  95479. }
  95480. // Clear out the extension before executing the action to avoid recursing into the same property.
  95481. delete extensions[this.name];
  95482. try {
  95483. return actionAsync(context + "/extensions/" + this.name, extension);
  95484. }
  95485. finally {
  95486. // Restore the extension after executing the action.
  95487. extensions[this.name] = extension;
  95488. }
  95489. };
  95490. /** Helper method called by the loader to allow extensions to override loading scenes. */
  95491. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  95492. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  95493. };
  95494. /** Helper method called by the loader to allow extensions to override loading nodes. */
  95495. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  95496. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  95497. };
  95498. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  95499. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  95500. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  95501. };
  95502. /** Helper method called by the loader to allow extensions to override loading materials. */
  95503. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, babylonDrawMode, assign) {
  95504. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); });
  95505. };
  95506. /** Helper method called by the loader to allow extensions to override loading uris. */
  95507. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  95508. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  95509. };
  95510. return GLTFLoaderExtension;
  95511. }());
  95512. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  95513. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  95514. })(BABYLON || (BABYLON = {}));
  95515. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  95516. "use strict";
  95517. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  95518. var BABYLON;
  95519. (function (BABYLON) {
  95520. var GLTF2;
  95521. (function (GLTF2) {
  95522. var Extensions;
  95523. (function (Extensions) {
  95524. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  95525. var NAME = "MSFT_lod";
  95526. var MSFT_lod = /** @class */ (function (_super) {
  95527. __extends(MSFT_lod, _super);
  95528. function MSFT_lod() {
  95529. var _this = _super !== null && _super.apply(this, arguments) || this;
  95530. _this.name = NAME;
  95531. /**
  95532. * Maximum number of LODs to load, starting from the lowest LOD.
  95533. */
  95534. _this.maxLODsToLoad = Number.MAX_VALUE;
  95535. _this._loadingNodeLOD = null;
  95536. _this._loadNodeSignals = {};
  95537. _this._loadingMaterialLOD = null;
  95538. _this._loadMaterialSignals = {};
  95539. return _this;
  95540. }
  95541. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  95542. var _this = this;
  95543. return this._loadExtensionAsync(context, node, function (context, extension) {
  95544. var firstPromise;
  95545. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  95546. var _loop_1 = function (indexLOD) {
  95547. var nodeLOD = nodeLODs[indexLOD];
  95548. if (indexLOD !== 0) {
  95549. _this._loadingNodeLOD = nodeLOD;
  95550. if (!_this._loadNodeSignals[nodeLOD._index]) {
  95551. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  95552. }
  95553. }
  95554. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  95555. if (indexLOD !== 0) {
  95556. var previousNodeLOD = nodeLODs[indexLOD - 1];
  95557. if (previousNodeLOD._babylonMesh) {
  95558. previousNodeLOD._babylonMesh.dispose(false, true);
  95559. delete previousNodeLOD._babylonMesh;
  95560. }
  95561. }
  95562. if (indexLOD !== nodeLODs.length - 1) {
  95563. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  95564. if (_this._loadNodeSignals[nodeIndex]) {
  95565. _this._loadNodeSignals[nodeIndex].resolve();
  95566. delete _this._loadNodeSignals[nodeIndex];
  95567. }
  95568. }
  95569. });
  95570. if (indexLOD === 0) {
  95571. firstPromise = promise;
  95572. }
  95573. else {
  95574. _this._loader._completePromises.push(promise);
  95575. _this._loadingNodeLOD = null;
  95576. }
  95577. };
  95578. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  95579. _loop_1(indexLOD);
  95580. }
  95581. return firstPromise;
  95582. });
  95583. };
  95584. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  95585. var _this = this;
  95586. // Don't load material LODs if already loading a node LOD.
  95587. if (this._loadingNodeLOD) {
  95588. return null;
  95589. }
  95590. return this._loadExtensionAsync(context, material, function (context, extension) {
  95591. var firstPromise;
  95592. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  95593. var _loop_2 = function (indexLOD) {
  95594. var materialLOD = materialLODs[indexLOD];
  95595. if (indexLOD !== 0) {
  95596. _this._loadingMaterialLOD = materialLOD;
  95597. if (!_this._loadMaterialSignals[materialLOD._index]) {
  95598. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  95599. }
  95600. }
  95601. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  95602. if (indexLOD !== 0) {
  95603. var babylonDataLOD = materialLOD._babylonData;
  95604. assign(babylonDataLOD[babylonDrawMode].material);
  95605. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  95606. if (previousBabylonDataLOD[babylonDrawMode]) {
  95607. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  95608. delete previousBabylonDataLOD[babylonDrawMode];
  95609. }
  95610. }
  95611. if (indexLOD !== materialLODs.length - 1) {
  95612. var materialIndex = materialLODs[indexLOD + 1]._index;
  95613. if (_this._loadMaterialSignals[materialIndex]) {
  95614. _this._loadMaterialSignals[materialIndex].resolve();
  95615. delete _this._loadMaterialSignals[materialIndex];
  95616. }
  95617. }
  95618. });
  95619. if (indexLOD === 0) {
  95620. firstPromise = promise;
  95621. }
  95622. else {
  95623. _this._loader._completePromises.push(promise);
  95624. _this._loadingMaterialLOD = null;
  95625. }
  95626. };
  95627. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  95628. _loop_2(indexLOD);
  95629. }
  95630. return firstPromise;
  95631. });
  95632. };
  95633. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  95634. var _this = this;
  95635. // Defer the loading of uris if loading a material or node LOD.
  95636. if (this._loadingMaterialLOD) {
  95637. var index = this._loadingMaterialLOD._index;
  95638. return this._loadMaterialSignals[index].promise.then(function () {
  95639. return _this._loader._loadUriAsync(context, uri);
  95640. });
  95641. }
  95642. else if (this._loadingNodeLOD) {
  95643. var index = this._loadingNodeLOD._index;
  95644. return this._loadNodeSignals[index].promise.then(function () {
  95645. return _this._loader._loadUriAsync(context, uri);
  95646. });
  95647. }
  95648. return null;
  95649. };
  95650. /**
  95651. * Gets an array of LOD properties from lowest to highest.
  95652. */
  95653. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  95654. if (this.maxLODsToLoad <= 0) {
  95655. throw new Error("maxLODsToLoad must be greater than zero");
  95656. }
  95657. var properties = new Array();
  95658. for (var i = ids.length - 1; i >= 0; i--) {
  95659. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  95660. if (properties.length === this.maxLODsToLoad) {
  95661. return properties;
  95662. }
  95663. }
  95664. properties.push(property);
  95665. return properties;
  95666. };
  95667. return MSFT_lod;
  95668. }(GLTF2.GLTFLoaderExtension));
  95669. Extensions.MSFT_lod = MSFT_lod;
  95670. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  95671. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  95672. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  95673. })(BABYLON || (BABYLON = {}));
  95674. //# sourceMappingURL=MSFT_lod.js.map
  95675. "use strict";
  95676. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  95677. var BABYLON;
  95678. (function (BABYLON) {
  95679. var GLTF2;
  95680. (function (GLTF2) {
  95681. var Extensions;
  95682. (function (Extensions) {
  95683. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  95684. var NAME = "KHR_draco_mesh_compression";
  95685. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  95686. __extends(KHR_draco_mesh_compression, _super);
  95687. function KHR_draco_mesh_compression(loader) {
  95688. var _this = _super.call(this, loader) || this;
  95689. _this.name = NAME;
  95690. _this._dracoCompression = null;
  95691. // Disable extension if decoder is not available.
  95692. if (!BABYLON.DracoCompression.DecoderUrl) {
  95693. _this.enabled = false;
  95694. }
  95695. return _this;
  95696. }
  95697. KHR_draco_mesh_compression.prototype.dispose = function () {
  95698. if (this._dracoCompression) {
  95699. this._dracoCompression.dispose();
  95700. }
  95701. _super.prototype.dispose.call(this);
  95702. };
  95703. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  95704. var _this = this;
  95705. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  95706. if (primitive.mode != undefined) {
  95707. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  95708. primitive.mode !== 4 /* TRIANGLES */) {
  95709. throw new Error(context + ": Unsupported mode " + primitive.mode);
  95710. }
  95711. // TODO: handle triangle strips
  95712. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  95713. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  95714. }
  95715. }
  95716. var attributes = {};
  95717. var loadAttribute = function (name, kind) {
  95718. var uniqueId = extension.attributes[name];
  95719. if (uniqueId == undefined) {
  95720. return;
  95721. }
  95722. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  95723. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  95724. babylonMesh._delayInfo.push(kind);
  95725. }
  95726. attributes[kind] = uniqueId;
  95727. };
  95728. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  95729. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  95730. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  95731. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  95732. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  95733. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  95734. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  95735. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  95736. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  95737. return _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  95738. try {
  95739. if (!_this._dracoCompression) {
  95740. _this._dracoCompression = new BABYLON.DracoCompression();
  95741. }
  95742. return _this._dracoCompression.decodeMeshAsync(data, attributes);
  95743. }
  95744. catch (e) {
  95745. throw new Error(context + ": " + e.message);
  95746. }
  95747. });
  95748. });
  95749. };
  95750. return KHR_draco_mesh_compression;
  95751. }(GLTF2.GLTFLoaderExtension));
  95752. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  95753. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  95754. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  95755. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  95756. })(BABYLON || (BABYLON = {}));
  95757. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  95758. "use strict";
  95759. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  95760. var BABYLON;
  95761. (function (BABYLON) {
  95762. var GLTF2;
  95763. (function (GLTF2) {
  95764. var Extensions;
  95765. (function (Extensions) {
  95766. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  95767. var NAME = "KHR_materials_pbrSpecularGlossiness";
  95768. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  95769. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  95770. function KHR_materials_pbrSpecularGlossiness() {
  95771. var _this = _super !== null && _super.apply(this, arguments) || this;
  95772. _this.name = NAME;
  95773. return _this;
  95774. }
  95775. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  95776. var _this = this;
  95777. return this._loadExtensionAsync(context, material, function (context, extension) {
  95778. material._babylonData = material._babylonData || {};
  95779. var babylonData = material._babylonData[babylonDrawMode];
  95780. if (!babylonData) {
  95781. var promises = new Array();
  95782. var name_1 = material.name || "materialSG_" + material._index;
  95783. var babylonMaterial = _this._loader._createMaterial(BABYLON.PBRMaterial, name_1, babylonDrawMode);
  95784. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  95785. promises.push(_this._loadSpecularGlossinessPropertiesAsync(context, material, extension, babylonMaterial));
  95786. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  95787. babylonData = {
  95788. material: babylonMaterial,
  95789. meshes: [],
  95790. loaded: Promise.all(promises).then(function () { })
  95791. };
  95792. material._babylonData[babylonDrawMode] = babylonData;
  95793. }
  95794. babylonData.meshes.push(babylonMesh);
  95795. assign(babylonData.material);
  95796. return babylonData.loaded;
  95797. });
  95798. };
  95799. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  95800. var promises = new Array();
  95801. if (properties.diffuseFactor) {
  95802. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  95803. babylonMaterial.alpha = properties.diffuseFactor[3];
  95804. }
  95805. else {
  95806. babylonMaterial.albedoColor = BABYLON.Color3.White();
  95807. }
  95808. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  95809. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  95810. if (properties.diffuseTexture) {
  95811. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  95812. babylonMaterial.albedoTexture = texture;
  95813. }));
  95814. }
  95815. if (properties.specularGlossinessTexture) {
  95816. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  95817. babylonMaterial.reflectivityTexture = texture;
  95818. }));
  95819. babylonMaterial.reflectivityTexture.hasAlpha = true;
  95820. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  95821. }
  95822. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  95823. return Promise.all(promises).then(function () { });
  95824. };
  95825. return KHR_materials_pbrSpecularGlossiness;
  95826. }(GLTF2.GLTFLoaderExtension));
  95827. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  95828. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  95829. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  95830. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  95831. })(BABYLON || (BABYLON = {}));
  95832. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  95833. "use strict";
  95834. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  95835. var BABYLON;
  95836. (function (BABYLON) {
  95837. var GLTF2;
  95838. (function (GLTF2) {
  95839. var Extensions;
  95840. (function (Extensions) {
  95841. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  95842. var NAME = "KHR_lights";
  95843. var LightType;
  95844. (function (LightType) {
  95845. LightType["AMBIENT"] = "ambient";
  95846. LightType["DIRECTIONAL"] = "directional";
  95847. LightType["POINT"] = "point";
  95848. LightType["SPOT"] = "spot";
  95849. })(LightType || (LightType = {}));
  95850. var KHR_lights = /** @class */ (function (_super) {
  95851. __extends(KHR_lights, _super);
  95852. function KHR_lights() {
  95853. var _this = _super !== null && _super.apply(this, arguments) || this;
  95854. _this.name = NAME;
  95855. return _this;
  95856. }
  95857. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  95858. var _this = this;
  95859. return this._loadExtensionAsync(context, scene, function (context, extension) {
  95860. var promise = _this._loader._loadSceneAsync(context, scene);
  95861. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  95862. if (light.type !== LightType.AMBIENT) {
  95863. throw new Error(context + ": Only ambient lights are allowed on a scene");
  95864. }
  95865. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  95866. return promise;
  95867. });
  95868. };
  95869. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  95870. var _this = this;
  95871. return this._loadExtensionAsync(context, node, function (context, extension) {
  95872. var promise = _this._loader._loadNodeAsync(context, node);
  95873. var babylonLight;
  95874. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  95875. var name = node._babylonMesh.name;
  95876. switch (light.type) {
  95877. case LightType.AMBIENT: {
  95878. throw new Error(context + ": Ambient lights are not allowed on a node");
  95879. }
  95880. case LightType.DIRECTIONAL: {
  95881. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  95882. break;
  95883. }
  95884. case LightType.POINT: {
  95885. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  95886. break;
  95887. }
  95888. case LightType.SPOT: {
  95889. var spotLight = light;
  95890. // TODO: support inner and outer cone angles
  95891. //const innerConeAngle = spotLight.innerConeAngle || 0;
  95892. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  95893. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  95894. break;
  95895. }
  95896. default: {
  95897. throw new Error(context + ": Invalid light type (" + light.type + ")");
  95898. }
  95899. }
  95900. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  95901. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  95902. babylonLight.parent = node._babylonMesh;
  95903. return promise;
  95904. });
  95905. };
  95906. Object.defineProperty(KHR_lights.prototype, "_lights", {
  95907. get: function () {
  95908. var extensions = this._loader._gltf.extensions;
  95909. if (!extensions || !extensions[this.name]) {
  95910. throw new Error("#/extensions: '" + this.name + "' not found");
  95911. }
  95912. var extension = extensions[this.name];
  95913. return extension.lights;
  95914. },
  95915. enumerable: true,
  95916. configurable: true
  95917. });
  95918. return KHR_lights;
  95919. }(GLTF2.GLTFLoaderExtension));
  95920. Extensions.KHR_lights = KHR_lights;
  95921. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  95922. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  95923. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  95924. })(BABYLON || (BABYLON = {}));
  95925. //# sourceMappingURL=KHR_lights.js.map
  95926. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  95927. globalObject["BABYLON"] = BABYLON
  95928. return BABYLON;
  95929. });